Run async code one after another by scheduling promises.

Overview

promise-scheduler

Run async code in a synchronous order by scheduling promises, with the possibility to cancel pending or active tasks. Optimized for the browser environment, less then 1KB in file size.

I came across a situation where I needed more fine-grained control over a sequence of async operations, with the added requirement that a single operational task should be abortable. Meaning that the task could abort earlier on in its execution in order for the next task to run. Think of a fetch call with an AbortController that makes the Promise resolve earlier due to the fact that the signal is cancelled along the way, but then in a sequence of multiple fetch calls.

A lot of the existing solutions do not take abortable operations into account, and they do too much for my liking (such as allowing concurrency). This is a lightweight yet limited implementation of a scheduler able to execute async code one after another.

Install

npm install @matpv91/promise-scheduler

API

import Scheduler from '@matvp91/promise-scheduler';

const scheduler = new Scheduler();

function createTask() {
  // Dummy function to define performing work over time.
  const work = () => new Promise(resolve => setTimeout(resolve, 500));

  return async (throwIfCanceled) => {
    await work();
    throwIfCanceled(); // Checks whether we can continue or discard the callstack below.
    await work();
    throwIfCanceled();
  };
}

// Schedule a task.
scheduler.scheduleCallback(createTask());

// Schedule a task with notifiers.
scheduler.scheduleCallback(createTask(), {
  onError: (error) => {}, // The task causes an error.
  onAborted: () => {}, // The task got aborted working.
});

// Pending (future) tasks are cancelled, and if a task
// is actively working, it gets aborted.
scheduler.flushWork();

// Returns a promise when no more work is pending.
scheduler.waitForIdle(): Promise

Lifecycle example

The example below illustrates a minimalistic Instance class with a load, unload and destroy lifecycle. The fact that the methods are async poses no risk of an unexpected side effect or race condition due to the fact that they're handled by a scheduler taking care of the order of execution.

class Instance {
  load() {
    this.unload();
    scheduler.scheduleCallback(/* an async, abortable task with plenty of work */);
  }

  unload() {
    scheduler.flushWork();
    scheduler.scheduleCallback(/* an async task for cleanup */);
  }

  async destroy() {
    this.unload();
    await scheduler.waitForIdle(); // Ensures no pending work is left.
  }
}
You might also like...

Run a command, watch the filesystem, stop the process on file change and then run the command again...

hubmon Run a command, watch the filesystem, stop the process on file change and then run the command again... Install You can install this command lin

Jul 30, 2022

Resolve parallel promises in key-value pairs whilst maintaining type information

async-kv Resolves promises in key-value pairs maintaining type information. Prerequisites NodeJS 12 or later Installation npm i async-kv yarn add asyn

Feb 17, 2022

🐶 Learn JS Promises, with your friend 👑 Princess!

🐶 Learn JS Promises, with your friend 👑 Princess!

Jun 9, 2022

Ajax library with XHR2, promises and request limit

qwest 4.5.0 ⚠ I finally decided to archive this repository. ⚠ At first, I developed Qwest because at the time other libraries were lacking of a proper

Sep 14, 2022

A request library that returns promises, inspired by request

then-request A request library that returns promises and supports both browsers and node.js Installation npm install then-request Usage request(metho

Nov 29, 2022

A polyfill for ES6-style Promises

ES6-Promise (subset of rsvp.js) This is a polyfill of the ES6 Promise. The implementation is a subset of rsvp.js extracted by @jakearchibald, if you'r

Dec 28, 2022

Remembering promises that were made!

remember-promise A simple utility to remember promises that were made! It is greatly inspired by the p-memoize utility but with additional built-in fe

Dec 15, 2022

Displaying actual age in percentage with 9 signs after dot (floating number)

Displaying actual age in percentage with 9 signs after dot (floating number)

Actual Age Chrome Extension Displaying actual age in percentage with 9 signs after dot (floating number) Features Popup You can select your Birth date

Nov 2, 2022

Save resources by suspending unused tabs after 20 min.

Tab Suspender [WIP] Save resources by suspending unused tabs after 20 min. Instalation Enable Epiphany extension. Optional if not done. Download the l

May 7, 2022
Comments
  • Allow sync run to be scheduled.

    Allow sync run to be scheduled.

    The following code would result in an exception:

    const syncTask = () => {};
    scheduler.scheduleCallback(syncTask);
    

    Due to the fact that the return value of task.run() expects a then() callback.

    opened by matvp91 0
Releases(v1.0.0)
Owner
Matthias
Show me the code.
Matthias
A Promise-compatible abstraction that defers resolving/rejecting promises to another closure.

Deferred Promise The DeferredPromise class is a Promise-compatible abstraction that defers resolving/rejecting promises to another closure. This class

Open Draft 21 Dec 15, 2022
A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable

JavaScript Iteration protocol workshop A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable by @loige.

Luciano Mammino 96 Dec 20, 2022
Habitat-for-humanity - A scheduling platform for Habitat for Humanity SLO to help with donation pickups.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Hack4Impact Cal Poly 4 Nov 4, 2022
Download all Moodle files with one click. This is a Chrome extension built to save time and effort from downloading files manually one by one!

Moodle Downloader Extension Moodle downloader extension for Chrome. The extension is tested with both the TUM moodle and the official moodle demo. Not

Zhongpin Wang 8 Nov 15, 2022
Change import URLs in JavaScript code using import maps. e.g. `import * from "before"` to `import * from "after"`

esm-import-transformer Can transform any ESM source code import URLs using an import maps object. This package works in ES modules or in CJS. // Befor

Zach Leatherman 19 Jul 31, 2022
Minimalistic configuration for TS to only extend JS with types. No TS features, no bundling. Readable maintainable code after compilation.

ts-guideline Minimalistic configuration for TS to only extend JS with types. No TS-scpecific features, no bundling. Readable maintainable code after c

Georg Oldenburger 41 Dec 22, 2022
Another logger in JS. This one offers a console.log-like API and formatting, colored lines and timestamps (or not if desired), all that with 0 dependencies.

hellog Your new logger ! hellog is a general-purpose logging library. It offers a console.log-like API and formatting, extensible type-safety colored

Maxence Lecanu 4 Jan 5, 2022
Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast.

equivalent-exchange Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast. Features Can parse code usin

Lily Scott 51 Jul 9, 2022
Send all tokens from one wallet to another quickly.

Drain Send all tokens from one wallet to another quickly. Whether getting hacked or starting fresh, Drain makes sure you get every last wei. Live Depl

Dawson Botsford 35 Dec 22, 2022