Sometimes, we want to time out a Promise if failed to complete in time with Node.js and JavaScript.
In this article, we’ll look at how to time out a Promise if failed to complete in time with Node.js and JavaScript.
How to time out a Promise if failed to complete in time with Node.js and JavaScript?
To time out a Promise if failed to complete in time with Node.js and JavaScript, we use the Promise.race
method.
For instance, we write
const withTimeout = (millis, promise) => {
const timeout = new Promise((resolve, reject) =>
setTimeout(() => reject(`Timed out after ${millis} ms.`), millis)
);
return Promise.race([promise, timeout]);
};
to define the withTimeout
function.
In it, we create the timeout
promise, which calls setTimeout
callback when millis
milliseconds has elapsed.
We call reject
to reject the promise.
Then we call Promise.race
with an array with the promise
we want to run and the timeout
promise.
Then the result of the promise that finishes first is returned as a promise.
Conclusion
To time out a Promise if failed to complete in time with Node.js and JavaScript, we use the Promise.race
method.