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-race-typescript

v2.2.2

Published

<div align="center"> <h1>⚡ Promise Race Typescript </h1> </div>

Downloads

56

Readme

Table of Contents

  1. Quick start guide
    1. Installing
    2. Importing
    3. Usage
      1. Typing the returned promise using typescript generics
      2. Single Promise
      3. Promise.all
      4. Promise.allSettled
      5. Combining timeoutPromise with Promise.allSettled
      6. Passing a timeoutPromise to a timeoutPromise
      7. Using abortController with timeoutPromise
  2. Contributing Code
    1. How to contribute summary
    2. Version Bumping
  3. Testing
  4. Changelog

🚀 Quick start guide

Installing


npm i promise-race-typescript

Importing

import { timeoutPromise } from 'promise-race-typescript';

Usage

You can race single promises, promise.all, promise.allSettled with the utility. You can combine it with promise.allSettled if you don't want to reject the promise.allSettled array of promises but be aware the failure was a timeout in one of the promises in the given array of promises. As it returns a promise, you can also pass a timeoutPromise to a timeoutPromise. Timeout promise (version 2.2.0 upwards) also accepts an abortController object instance, which could be paired with a fetch request promise (for example) to call .abort() on the abortController object instace associated with the given fetch if the timeout is hit.

Example usage with an abortController object:

const ac = new AbortController();

const { signal } = ac.signal;

const promise = fetch(someUrl, { signal }).then((response) => response.json());

const example = timeoutPromise({ promise, timeout: 2000, errorMessage: 'your error message', abortController: ac });

Some more detailed examples are presented below:

Typing the returned promise using Typescript generics

const promise = new Promise((resolve) => setTimeout(() => resolve('resolved'), 3000)) as Promise<string>;
await timeoutPromise<number>({ promise, timeout: 2000, message: 'foo' })); // compile time error (Promise<number> cannot be assigned to type Promise<string>)

Single Promise

const promise = new Promise((resolve) => setTimeout(() => resolve('resolved'), 3000));
await timeoutPromise({ promise, timeout: 2000, message: 'foo' })); // rejects with new TimeoutError('foo')

const promise = new Promise((resolve) => setTimeout(() => resolve('resolved'), 3000));
await timeoutPromise({ promise, timeout: 10000, message: 'foo' })); // resolves with 'resolved'

Promise.all

const promises = [1, 2, 3].map(
    (value) => new Promise((resolve) => setTimeout(() => resolve(Math.pow(value, 2)), value))
);
const promiseAll = Promise.all(promises);
await timeoutPromise({
    promise: promiseAll,
    timeout: 2500,
    errorMessage: 'test error',
}); // [1,4,9]

// Note, you could also achieve this by simply having one of the promises in the promise.all array of promises
// be a setTimeout that rejects after the desired gestation, but this is arguably an easier to read solution.
const promises = [1, 2, 3].map(
    (value) => new Promise((resolve) => setTimeout(() => resolve(Math.pow(value, 2)), value * 1000))
);
const promiseAll = Promise.all(promises);
await timeoutPromise({
    promise: promiseAll,
    timeout: 2500,
    errorMessage: 'test error',
}); // rejects with new TimeoutError('test error')

Promise.allSettled

const promises = [1, 2, 3].map(
    (value) => new Promise((resolve) => setTimeout(() => resolve('resolved'), value * 1000))
);
const promiseAllSettled = Promise.allSettled(promises);
await timeoutPromise({
    promise: promiseAllSettled,
    timeout: 2500,
    errorMessage: 'test error',
}); // rejects with new TimeoutError('test error')

const promises = [1, 2, 3].map(
    (value) => new Promise((resolve) => setTimeout(() => resolve(Math.pow(value, 2)), value))
);
const promiseAllSettled = Promise.allSettled(promises);
const foo = await timeoutPromise({
    promise: promiseAllSettled,
    timeout: 2500,
    errorMessage: 'test error',
});

// foo =
// [
//     {
//         status: 'fulfilled',
//         value: 1,
//     },
//     {
//         status: 'fulfilled',
//         value: 4,
//     },
//     {
//         status: 'fulfilled',
//         value: 9,
//     },
// ];

Combining timeoutPromise with Promise.allSettled

const promises = [1, 2, 3, 4, 5].map(
    (value) =>
        new Promise((resolve, reject) =>
            setTimeout(
                () => (value === 3 ? reject(new Error('rejected!')) : resolve(Math.pow(value, 2))),
                value === 4 ? 3000 : 1
            )
        )
);

const promisesWithIndividualTimers = promises.map((promise) => timeoutPromise({ promise, timeout: 2500 }));

const promiseAllSettledWithTimeout = Promise.allSettled(promisesWithIndividualTimers);

const foo = await promiseAllSettledWithTimeout;

// foo =
// [
//     {
//         status: 'fulfilled',
//         value: 1,
//     },
//     {
//         status: 'fulfilled',
//         value: 4,
//     },
//     {
//         status: 'rejected',
//         reason: new Error('rejected!'),
//     },
//     {
//         status: 'rejected',
//         reason: new TimeoutError('Timeout in timeoutPromise fn'),
//     },
//     {
//         status: 'fulfilled',
//         value: 25,
//     },
// ];

Passing a timeoutPromise to a timeoutPromise

const promise = new Promise((resolve) => setTimeout(() => resolve('resolved'), 3000));
const tPromise = timeoutPromise({ promise, timeout: 2000, errorMessage: 'inner timeout promise' });
await timeoutPromise({ promise: tPromise, timeout: 1000, errorMessage: 'outer timeout promise' }); // rejects with new TimeoutError('outer timeout promise')
await timeoutPromise({ promise: tPromise, timeout: 3000, errorMessage: 'outer timeout promise' }); // rejects with new TimeoutError('innner timeout promise')

Using abortController with timeoutPromise

Simply pass through the controller to the timeoutPromise.

const ac = new AbortController();

const { signal } = ac.signal;

const promise = fetch(someUrl, { signal }).then((response) => response.json());

const withAbortController = await timeoutPromise({
    promise,
    timeout: 2000,
    errorMessage: 'an error message',
    abortController: ac,
});

📝 Contributing Code

How to contribute summary

  • Create a branch from the develop branch and submit a Pull Request (PR)
    • Explain what the PR fixes or improves
  • Use sensible commit messages which follow the Conventional Commits specification.
  • Use a sensible number of commit messages

Version Bumping

Our versioning uses SemVer and our commits follow the Conventional Commits specification.

  1. Make changes
  2. Commit those changes
  3. Pull all the tags
  4. Run npm version [patch|minor|major]
  5. Stage the CHANGELOG.md, package-lock.json and package.json changes
  6. Commit those changes with git commit -m "chore(): bumped version to $version"
  7. Push your changes with git push and push the tag with git push origin $tagname where $tagname will be v$version e.g. v1.0.4

✅ Testing

Coverage lines Coverage functions Coverage branches Coverage statements

  1. Clone the repository

  2. Install dependencies: npm ci

  3. Test: npm test

📘 Changelog

See CHANGELOG.md