⚡ 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.
Table of Contents
🚀 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.
- Make changes
- Commit those changes
- Pull all the tags
- Run
npm version [patch|minor|major]
- Stage the
CHANGELOG.md
,package-lock.json
andpackage.json
changes - Commit those changes with
git commit -m "chore(): bumped version to $version"
- Push your changes with
git push
and push the tag withgit push origin $tagname
where$tagname
will bev$version
e.g.v1.0.4
✅ Testing
-
Clone the repository
-
Install dependencies:
npm ci
-
Test:
npm test
📘 Changelog
See CHANGELOG.md