promise-more

1.0.29 • Public • Published

promise-more

A well-tested library for handling Promises with Flow type declarations and carefully thought out API.

Compatible with Node v6.11.2 LTS or later.

Contributions welcome!

Installation

npm install --save promise-more

Usage examples

With async/await - recommended

const { delay } = require('promise-more');
 
async function main() {
  console.log('Hello...');
  await delay(500); // wait half a second
  console.log('...world!');  
}
 
main();

Without async/await

const { delay } = require('promise-more');
 
console.log('Hello...');
delay(500).then(() => { // wait half a second
  console.log('...world!');
});

API

Table of Contents

CONTROL FLOW

Functions to control how asynchronous tasks are executed.

Task

Task is a function that returns a Promise of value (asynchronous execution) or the value itself (synchronous execution).

This type definition is used by all the control flow functions.

Type: function (args: P): (Promise<T> | T)

Examples

// once run, it waits 1s and then logs 'Hello!'
const task: Task<void, void= async () => {
  await delay(1000);
  console.log('Hello!'));
};

scheduler

Scheduler enqueues tasks to be run in accordance with the options passed.

Scheduler options (all optional):

  • limit number The limit of tasks that can be run simultaneously (default 1)

Task execution options (all optional):

  • immediate boolean Whether the task should be run immediately disregarding the queue (default false)
  • priority number Priority (the higher the value, the sooner task is run) (default 0)
  • context any data you want make available to the task at the time of execution (default undefined)
  • taskIndex number run this task immediately with the same arguments as currently pending task with given index (default undefined). Tasks run this way are not included in statistics and other execution options are ignored.

Tasks are executed with a single object argument which contains the following properties:

  • index number The sequence number of the task being run (starts with 0)
  • workerNr number The number of worker (0..(limit-1)) who should get this task. For immediate tasks it is equal to -1 - they are usually handled by some extra resources.
  • fulfilled number Number of fulfilled tasks
  • rejected number Number of rejected tasks
  • pending number Number of tasks currently running (including immediate ones). Always positive.
  • waiting number Number of tasks still in the queue
  • options Task options with default values
  • schedulerOptions Scheduler options with default values

Parameters

  • schedulerOptions $Shape<SchedulerOptions>

Examples

// runs two given tasks sequentially
const schedule = scheduler();
schedule(async () => {
  await delay(1000);
  console.log('A second has passed');
});
 
schedule(async () => {
  await delay(2000);
  console.log('Two more seconds have passed');
});
// runs tasks in parallel with the limit provided
function parallelLimit(tasks, limit) {
  const schedule = scheduler({ limit });
  return Promise.all(tasks.map(t => schedule(t)));
}
// runs tasks sequentially and resolves to an array of results
function series(tasks) {
  const schedule = scheduler();
  return Promise.all(tasks.map(t => schedule(t)));
}

Returns function (task: Task<T, RunParameters<C>>, options: $Shape<TaskOptions<C>>): Promise<T>

sequence

Runs tasks sequentially. The next one is run only after previous was resolved. Rejects immediately if any task rejects.

Parameters

Examples

// prints "Hello world" one letter at a time
sequence(
  'Hello world'.split('').map(c => () => delayedLog(c))
);
 
async function delayedLog(s) {
  await delay(50);
  console.log(s);
}

Returns Promise<void>

UTILITIES

Other utility functions.

after

Runs task after promise was resolved or rejected (like finally).

Parameters

  • promise Promise<T> The promise after which to run the task
  • task Task<void, PromiseState<T>> The task to run after the promise. Called with result of state of the promise (fulfilled or rejected). If the task throws, the error is propagated to the promise returned from after.

Examples

const taskWithCleanup = () => after(operation(), cleanup);
 
// same as
const taskWithCleanup = async () => {
  try {
    return await operation();
  } finally {
    await cleanup(); // no way to know if the task succeded
  }
}

Returns Promise<T>

delay

Waits for given time and then resolves with undefined.

Parameters

  • ms number The number of milliseconds to wait (default 0)

Examples

async function main() {
  // ...
  await delay(1000); // halt execution for one second
  // ...
}

Returns Promise<void>

delayedReject

Waits for given time and then rejects with given reason.

Parameters

  • reason any The reason to reject
  • ms number The number of milliseconds to wait (default 0)

Returns Promise<any>

delayedResolve

Waits for given time and then resolves with given value.

Parameters

  • value (Promise<T> | T) The value to resolve to
  • ms number The number of milliseconds to wait (default 0)

Returns Promise<T>

state

Asynchronous API for checking state of the promise. The returned promise is fulfilled as soon as possible.

Note: there is no public synchronous API for this.

Parameters

  • promise Promise<T> The promise to determine the state of.

Returns Promise<PromiseState<T>>

PromiseState

Type: ({name: "pending"} | {name: "fulfilled", value: T} | {name: "rejected", reason: any})

timeout

Rejects with instance of TimeoutError if promise doesn't resolve within the specified time. Resolves with the value of promise otherwise.

Parameters

  • promise Promise<T> The promise to put time constraint on
  • ms number The number of milliseconds to wait

Examples

// rejects if npmjs.com isn't fetched within 100 ms
timeout(fetch('https://www.npmjs.com/'), 100);

Returns Promise<T>

ERRORS

Possible errors.

TimeoutError

Extends BaseError

Timeout

BaseError

Extends Error

Parameters

Package Sidebar

Install

npm i promise-more

Weekly Downloads

3

Version

1.0.29

License

MIT

Last publish

Collaborators

  • mhagmajer