npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

promise-more

v1.0.29

Published

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

Downloads

21

Readme

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