Loading...
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Timeout')), 5000);
});
const result = await Promise.race([task(), timeout]);let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error('Timeout')), 5000);
});
const result = await Promise.race([task(), timeout])
.finally(() => clearTimeout(timer));Clearing the timer in finally() stops a pending timeout from firing after the task has already won the race.
setTimeout() running after the main task wins.fetch() timeouts use AbortSignal.timeout(), so the request is actually canceled, not just ignored.Promise.race() cancel the slower promises?No. Promises cannot be canceled; the other operations keep running and their results are ignored. Use an AbortSignal to stop them.
Promise.race()?The returned promise stays pending forever, because nothing can settle it.