Sub topic 8
Promise.race: The First Promise to Settle Decides
This chapter assumes you know how promises move from pending to fulfilled or rejected. It also assumes you can use async/await with try/catch, and that you understand that combinators take an iterable and return one promise.
Promise.race returns a promise that settles as soon as any input settles. Whatever happens to that first input also happens to the returned promise. If the first input to settle fulfills, the race fulfills with its value. If it rejects, the race rejects with its reason.
The Rule: Settlement, Not Success
Promise.race makes no distinction between success and failure. The earliest settlement decides the result, and it can be either kind. This is the main difference between race and Promise.any, which waits for the first fulfillment and skips over rejections.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
// The fastest input fulfills, so the race fulfills
const winner = await Promise.race([delay(200, 'slow'), delay(50, 'fast')]);
console.log(winner); // 'fast'
// The fastest input rejects, so the race rejects
try {
await Promise.race([delay(200, 'slow'), fail(50, 'early failure')]);
} catch (err) {
console.log(err.message); // 'early failure'
}
}
main();In the second race, the 200 ms promise would have fulfilled, but that doesn't matter. The rejection at 50 ms settled first, so the race had already ended.
Ties and Plain Values
When several inputs have already settled before you call race, the result goes to the first of them in iteration order. A plain value counts as an already-fulfilled promise, so it can win a race:
async function main() {
const result = await Promise.race([delay(10, 'timer'), 'plain value']);
console.log(result); // 'plain value'
const order = await Promise.race([Promise.resolve('first'), Promise.resolve('second')]);
console.log(order); // 'first'
}
function delay(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
main();Don't rely on this ordering for real work. Order usually depends on timing you don't control, such as network latency.
The Losers Keep Running
The race ends when one input settles, but the other operations do not stop. Their timers still fire, their requests still complete, and their side effects still happen. The race simply ignores what they produce. A rejection from a losing promise also counts as handled, so it won't trigger an unhandled-rejection warning.
When to Use It
| Situation | Is `race` a good fit? |
|---|---|
| Give up on an operation after a deadline | Yes, race the operation against a rejecting timer |
| Use the first server to respond successfully | No, use `Promise.any`, because one fast failure would end the race |
| React to whichever of several events happens first | Yes, if a failure should also end the wait |
| Collect every result | No, use `Promise.all` or `Promise.allSettled` |
Exercise
What does this code log, and roughly when? Promise.race([delay(100, 'A'), fail(30, 'B down'), delay(10, 'C')]).then(console.log, (e) => console.log('error:', e.message));
Show answer
It logs 'C' after about 10 ms. The 10 ms promise settles first, and it fulfills, so the race fulfills with 'C'. The rejection at 30 ms and the fulfillment at 100 ms come later and are ignored, but their timers still run.
Exercise
You race three mirror requests to download a file. The first mirror returns an error in 5 ms, and the other two would succeed in about 80 ms. Why does Promise.race give the wrong behavior here, and what should you use instead?
Show answer
Promise.race adopts the first settlement, so the 5 ms error rejects the whole race even though two mirrors would have succeeded. Use Promise.any, which ignores rejections until one input fulfills.