Promise.race is useful if you want to run multiple promises, and either…
That is, if one of the promises rejects, you want to preserve that rejection to treat the error case separately. The following second example does exactly that.
// first example - load document and if this operation will be slower than 1000ms run second promise
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(reject, ms);
})
}
Promise.race([readFilePromise('index.html'), timeout(1000)])
.then(data => console.log(data))
.catch(e => console.log("Timed out after 1 second"));
//second example
try {
const result = await Promise.race([
performHeavyComputation(),
rejectAfterTimeout(2000),
]);
renderResult(result);
} catch (error) {
renderError(error);
}