Promises - Race Method
Promise.race() takes a list of promises and returns one promise, which settles the same way as the first promise in the list to settle. If the first to finish is fulfilled, the race is fulfilled with its value, and if the first to finish is rejected, the race is rejected with its reason.
Use it when only the quickest answer matters, or to put a time limit on slow work.
The first to finish wins
Section titled “The first to finish wins”The examples use a wait() helper that fulfils after a delay:
const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
Promise.race([wait(200, 'north mirror'), wait(100, 'south mirror')]).then((mirror) => console.log(`Downloading from the ${mirror}`),);This prints:
Downloading from the south mirrorA rejection can win too
Section titled “A rejection can win too”Promise.race() does not wait for a success. If a rejection comes first, it decides the result:
const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));const fail = (ms, message) => new Promise((resolve, reject) => setTimeout(reject, ms, new Error(message)));
Promise.race([wait(200, 'north mirror'), fail(50, 'East mirror refused the connection')]) .then((mirror) => console.log(`Downloading from the ${mirror}`)) .catch((error) => console.log('Failed:', error.message));This prints:
Failed: East mirror refused the connectionTo take the first success and ignore failures, use Promise.any() instead.
Adding a timeout
Section titled “Adding a timeout”Racing slow work against a promise that rejects after a delay gives the work a deadline:
const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const timeout = (ms) => new Promise((resolve, reject) => { setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms); });
const buildReport = () => wait(500, 'Quarterly report');
Promise.race([buildReport(), timeout(200)]) .then((report) => console.log('Got', report)) .catch((error) => console.log(error.message));This prints:
Timed out after 200 msThe losing promises are not cancelled. Here the report is still built after 500 milliseconds, and its result is simply ignored. For fetch(), a better way to set a deadline is to pass signal: AbortSignal.timeout(200) in its options, because that also stops the request.
Pitfalls
Section titled “Pitfalls”Promise.race([])with an empty list never settles, so any code waiting on it waits forever.- A plain value in the list counts as already fulfilled, so it beats every promise that is still pending. Where the list holds several values or promises that have already settled, the one earliest in the list wins.
Steve Griffith covers this topic in his video JavaScript Promise race method.