45
loading...
This website collects cookies to deliver better user experience
never
which represents the type of values that never occur. For instance, never
is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns.// create a promise that rejects in milliseconds
const timeout = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(timeoutError);
}, ms);
});
Promise
that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. Here you can see that we have used <T>
generic type that it will be defined in our final function.Promise.race<T>([anyPromise, anyOtherPromise]);
function promiseWithTimeout<T>(
promise: Promise<T>,
ms: number,
timeoutError = new Error('Promise timed out')
): Promise<T> {
// create a promise that rejects in milliseconds
const timeout = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(timeoutError);
}, ms);
});
// returns a race between timeout and the passed promise
return Promise.race<T>([promise, timeout]);
}
promise
: our actual promisems
: the maximum time in milliseconds which we want to waittimeoutError
: (optional) we may pass a custom error to throw after timeout