To time out a Node Promise if failed to complete in time, we use the Promise race
method.
For instance, we write
const race = Promise.race([
new Promise((resolve) => {
setTimeout(() => {
resolve("I did it");
}, 1000);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject("Timed out");
}, 800);
}),
]);
try {
const data = await race;
} catch (e) {
console.log(e);
}
to call Promise.race
with an array of promises.
We call reject
in the 2nd Promise
callback to reject the promise after 800ms.
Then we use await
to run the promise returned by race
.
And then we get the data
from the promise.
We catch the rejection with the catch block.