JavaScriptMedium
What is Promise.race()?
Promise.race(iterable) returns a promise that settles the same way as the first input promise to settle, whether that first one fulfills or rejects.
Typical uses
- Timeouts: race the real operation against a promise that rejects after N milliseconds.
- Fastest source wins: query a cache and the network and use whichever answers first (though
Promise.anyis usually better here, because it ignores failures). - Cancellation signals: race work against a promise that rejects when the user navigates away.
race vs any
race: the first to settle wins, even if it is a failure.any: the first to succeed wins; it rejects only if every promise fails (with anAggregateError).
Important caveats
- The losers keep running. A timed-out
fetchstill completes in the background and still uses bandwidth. To actually stop it, use anAbortController(fetch(url, { signal })). For simple timeouts,AbortSignal.timeout(ms)does both in one step. - An empty iterable gives a promise that stays pending forever.
- Clear your timeout timer when the real operation wins, or it keeps the process (or test runner) alive.
Modern timeout pattern
fetch(url, { signal: AbortSignal.timeout(5000) }) rejects with a TimeoutError and cancels the request, which is cleaner than a race for fetch specifically. Promise.race remains the general tool for any promise.
Code example
js
1const wait = (ms, value, fail = false) =>2 new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));34console.log(await Promise.race([wait(50, "slow"), wait(10, "fast")])); // fast56// The first to settle wins, even if it's a rejection7try {8 await Promise.race([wait(30, "ok"), wait(10, "failed first", true)]);9} catch (e) {10 console.log("rejected:", e.message); // rejected: failed first11}1213// Reusable timeout helper (clears its timer when the work wins)14function withTimeout(promise, ms) {15 let timer;16 const timeout = new Promise((_, reject) => {17 timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms);18 });19 return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));20}2122console.log(await withTimeout(wait(10, "in time"), 100)); // in time23try {24 await withTimeout(wait(200, "too late"), 30);25} catch (e) {26 console.log(e.message); // Timed out after 30ms27}2829// any: first SUCCESS wins, failures are ignored30console.log(await Promise.any([wait(5, "x", true), wait(20, "first success")])); // first success
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.