promise-race-typescript
TypeScript icon, indicating that this package has built-in type declarations

2.2.2 • Public • Published

Promise Race Typescript

A simple Typescript wrapper for Promise.race that takes a promise to race against (e.g. a fetch api request), a timeout period in ms (e.g. 6000 for 6 seconds), an optional error message to be displayed when/if the promise is rejected because the timeout is hit, and an optional abortController object. As it's typescript, the return type of the promise can be set using generics.


The flash gif


CI pipeline badge npmjs promise-race-typescript

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


Package Sidebar

Install

npm i promise-race-typescript

Weekly Downloads

1

Version

2.2.2

License

none

Unpacked Size

33.5 kB

Total Files

10

Last publish

Collaborators

  • liggles