<div align="center"> <h1>ā” Promise Race Typescript </h1> </div>
npm install 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.
npm i promise-race-typescript
`
Importing
`ts
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:
`ts
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:
$3
`ts
const promise = new Promise((resolve) => setTimeout(() => resolve('resolved'), 3000)) as Promise;
await timeoutPromise({ promise, timeout: 2000, message: 'foo' })); // compile time error (Promise cannot be assigned to type Promise)
`
$3
`ts
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'
`
$3
`ts
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')
`
$3
`ts
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,
// },
// ];
`
$3
`ts
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,
// },
// ];
`
$3
`ts
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')
`
$3
Simply pass through the controller to the timeoutPromise.
`ts
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
$3
- 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
$3
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`