Sub topic 8
Promise.race: The First Promise to Settle Decides
This chapter assumes you know how to create promises, consume them with await and try/catch, and understand that a promise settles once, either by fulfilling or rejecting. You should also be comfortable with the shared combinator model from earlier chapters, where an iterable goes in and one promise comes out.
Promise.race is the simplest combinator to describe. It returns a promise that settles the same way as the first input to settle. If that input fulfills, the race fulfills with its value. If it rejects, the race rejects with its reason. The remaining inputs do not affect the result.
The Settlement Rule
Promise.race does not care whether the first settlement is a success or a failure. That makes it different from Promise.any, which waits for the first fulfillment and skips rejections. With race, an early rejection wins just as easily as an early fulfillment.
// Save as race-basics.mjs and run with: node race-basics.mjs
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
// The fastest fulfillment wins
const winner = await Promise.race([delay(200, 'slow'), delay(50, 'fast')]);
console.log(winner); // 'fast'
// A rejection that settles first also wins
try {
await Promise.race([delay(200, 'slow'), fail(50, 'early failure')]);
} catch (err) {
console.log(err.message); // 'early failure'
}
// A rejection that settles later is ignored
const stillFast = await Promise.race([delay(50, 'fast'), fail(200, 'late failure')]);
console.log(stillFast); // 'fast'The table lists the possible outcomes for two inputs, A and B, where A settles before B.
| A settles first by | B settles later by | Result of `Promise.race([A, B])` |
|---|---|---|
| Fulfilling with `x` | Fulfilling | Fulfills with `x` |
| Fulfilling with `x` | Rejecting | Fulfills with `x` |
| Rejecting with `e` | Fulfilling | Rejects with `e` |
| Rejecting with `e` | Rejecting | Rejects with `e` |
B never matters in any row. Once the race has settled, nothing can change its result.
How It Works Inside
A simplified version of Promise.race takes only a few lines, and it accounts for nearly all of the combinator's behavior:
function myRace(iterable) {
return new Promise((resolve, reject) => {
for (const item of iterable) {
Promise.resolve(item).then(resolve, reject);
}
});
}
const result = await myRace([
new Promise((resolve) => setTimeout(() => resolve('one'), 100)),
new Promise((resolve) => setTimeout(() => resolve('two'), 20))
]);
console.log(result); // 'two'Several behaviors follow from this sketch:
- One settlement only. The same
resolveandrejectpair goes to every input. A promise's resolving functions only take effect on their first call, so the first input to call one of them decides the result. Later calls do nothing. - Plain values are accepted. Each item goes through
Promise.resolve, so42or'cached'becomes an already-fulfilled promise. - Loser rejections are handled. Every input gets a rejection handler (
reject), so a losing input that rejects later does not trigger an unhandled-rejection warning in Node.js or the browser. - An empty iterable never settles. With no items, nobody calls
resolveorreject, so the returned promise stays pending forever. The edge-cases chapter covers this in more detail.
The real implementation also reads this so subclasses work, and it handles errors that happen while iterating. If you pass something that is not iterable, such as a single promise, you get back a rejected promise with a TypeError. The call does not throw synchronously.
try {
await Promise.race(Promise.resolve(1)); // forgot the array
} catch (err) {
console.log(err instanceof TypeError); // true
}The Losers Keep Running
Winning the race does not stop the other operations. Promise.race only decides which result you get. Timers, network requests, and file reads that are already underway keep going, and they keep using resources.
function task(name, ms) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`${name} finished`);
resolve(name);
}, ms);
});
}
const start = Date.now();
const winner = await Promise.race([task('A', 100), task('B', 300)]);
console.log(`winner: ${winner} after ~${Date.now() - start} ms`);
// Output:
// A finished
// winner: A after ~100 ms
// B finished <- about 200 ms later; B was never stoppedIn Node.js, a pending loser can also keep the process alive. The script above exits only after B's timer fires. This causes real trouble when the losing operation has side effects, such as a request that writes to a database, or when it holds a resource like a socket. The later chapter on AbortController shows how to cancel the losing operations explicitly.
Ties and Already-Settled Inputs
If two inputs are already settled when you call race, the one that comes first in the iterable wins. Their reaction jobs go into the microtask queue in iteration order.
const first = await Promise.race([Promise.resolve('a'), Promise.resolve('b')]);
console.log(first); // 'a'
// A plain value counts as already fulfilled, so it beats any real pending work
const cached = await Promise.race([
new Promise((resolve) => setTimeout(() => resolve('network'), 10)),
'cached'
]);
console.log(cached); // 'cached'That rule holds only for inputs that are already settled. A promise that will settle "immediately" can still lose to an input that comes later in the array, because it may need more microtask steps:
const tricky = await Promise.race([
Promise.resolve().then(() => 'a'), // still pending when race is called
'b' // already fulfilled
]);
console.log(tricky); // 'b'The first input is pending when race attaches its handler. It fulfills during a microtask, and only then does it schedule race's handler. By that time, the handler for 'b' has already run. Promises returned by async functions often take extra steps like this too. If your logic depends on which of two near-instant promises wins, rewrite it so it does not. Microtask ordering is an implementation detail of how your promises are built, and it is not a contract you can rely on.
When Race Is the Right Tool
Use Promise.race when the first settlement of any kind should decide what happens next:
- Deadlines. Race the real work against a promise that rejects after a delay. If the timer settles first, the caller gets a timeout error. The next chapter builds this pattern step by step, including how to clear the timer.
- Stop signals. Race a long operation against a promise that settles when the user clicks Cancel or the server begins shutting down. Whichever happens first decides the flow.
- First event of several. Wait for whichever of several one-shot events fires first, for example a
loadevent versus anerrorevent, each wrapped in a promise.
Do not use race when you want the first success from redundant sources, such as several mirrors of the same file. A mirror that fails fast would win the race and reject the whole operation, even if another mirror was about to succeed. Promise.any exists for that case.
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const mirrors = () => [fail(10, 'mirror A down'), delay(50, 'data from B')];
try {
await Promise.race(mirrors());
} catch (err) {
console.log('race:', err.message); // 'race: mirror A down'
}
console.log('any:', await Promise.any(mirrors())); // 'any: data from B'Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Assuming the winner must be a fulfillment | An early rejection rejects the race | Use `Promise.any`, or make sure only the intended input can reject |
| Expecting losers to stop | Requests and timers keep running and keep the process alive | Cancel them with `AbortController` or `clearTimeout` |
| Passing an empty array built from a filter | The race stays pending forever | Check the length before racing |
| Passing a single promise instead of an array | The race rejects with `TypeError` | Wrap the inputs in an array |
| Relying on which near-instant promise wins | The winner depends on microtask scheduling | Remove the dependency on ordering |
Exercise
What does this code log, and roughly when? const r = Promise.race([new Promise((_, rej) => setTimeout(() => rej(new Error('x')), 100)), new Promise((res) => setTimeout(() => res('y'), 30))]); r.then(v => console.log('ok', v), e => console.log('err', e.message));
Show answer
It logs "ok y" after about 30 ms. The fulfillment at 30 ms settles first, so the race fulfills with 'y'. The rejection at 100 ms arrives after the race has settled. The race ignores it, and because race attached a rejection handler, it does not cause an unhandled-rejection warning.
Exercise
You call Promise.race([fetch(urlA), fetch(urlB)]) to fetch the same JSON from two servers. Server A responds immediately with a network error, and server B would have succeeded 200 ms later. What does the caller get, and what should you change?
Show answer
The caller gets a rejection with A's network error, because a rejection that settles first wins the race. The request to B also keeps running in the background. Use Promise.any so the first successful response wins. To stop the losing request after the winner arrives, pass a shared AbortController signal to both fetch calls and abort it.
Exercise
Using only Promise.resolve and the Promise constructor, explain why myRace([]) never settles and why a losing input that rejects does not produce an unhandled rejection.
Show answer
myRace calls resolve or reject only from handlers attached to the items. With no items, no handler is ever attached, so the returned promise stays pending. Each item gets Promise.resolve(item).then(resolve, reject), so every input has a rejection handler. A later rejection runs reject, which has no effect because the race has already settled, and the rejection counts as handled.