Node.js
Promise.race
Learn to await the first to finish with Promise.race.
What is Promise.race?
Promise.race takes an array of Promises and returns the result of the first one to settle (fulfilled or rejected). It works like a race: the first to finish wins and its result becomes the result of the whole race call. The other Promises still run but their results are ignored.
Promise.race([fast, slow])
.then(winner => console.log(winner));
This method is useful to put a timeout on an operation: you race the main work against a timeout Promise; if the timeout finishes first, you get an error.
The timeout pattern
A common use of Promise.race is to put a timeout on long operations. You race the main work against a timeout Promise that rejects after a fixed delay. If the work finishes before the timeout, race fulfils with its result; if the timeout fires first, race rejects with an error.
function timeout(ms) {
return new Promise((_, reject) =>
setTimeout(() => reject(new Error("timeout")), ms)
);
}
Here timeout(1000) rejects after 1000 ms; racing the main work against it gives an error if the work takes longer than a second.
Exercise Your turn: first result with Promise.race
Create two Promises: const fast = new Promise(res => setTimeout(() => res("fast"), 10)) and const slow = new Promise(res => setTimeout(() => res("slow"), 50)). Call Promise.race([fast, slow]) and log the winner with .then(winner => console.log(winner)).
Show example solution
const fast = new Promise(res => setTimeout(() => res("fast"), 10));
const slow = new Promise(res => setTimeout(() => res("slow"), 50));
Promise.race([fast, slow]).then(winner => console.log(winner));
Test yourself
-
Promise.race concepts
- race
- first to settle
- timeout
- time limit
- winner
- race winner
-
If the first of two Promises rejects, what does Promise.race return?
- It waits for the second Promise
- It returns an empty value
- It immediately rejects with that error
- It creates a new Promise
Show answer
It immediately rejects with that error — If the first to settle is a rejection, race rejects too.
-
Fill in the blank: Promise.race
const a = Promise.resolve("a");
const b = Promise.resolve("b");
____([a, b]).then(winner => console.log(winner));
Show answer
const a = Promise.resolve("a");
const b = Promise.resolve("b");
Promise.race([a, b]).then(winner => console.log(winner));
Next lesson: finally