Promise.race() returns a promise that settles as soon as any of the input promises settlesβwhether it resolves or rejects. The first promise to complete "wins the race" and determines the outcome.
π§ Understanding Promise.race
Atom 1: Purpose
Promise.race returns a promise that settles as soon as any input promise settles β resolved or rejected.
First one wins β race ends immediately.
Atom 2: Inputs
- Takes an iterable (usually an array) of promises or values
- Wrap each with
Promise.resolve()to normalize non-promises
Atom 3: Core Logic
- Attach
.then(resolve)and.catch(reject)to each input - As soon as any one settles , resolve/reject outer promise
- Ignore later results
Atom 4: Edge Case
- If input is empty , the returned promise never settles
β
Implementation: promiseRace
function promiseRace(iterable) { return new Promise((resolve, reject) => { for (const item of iterable) { Promise.resolve(item) .then(resolve) .catch(reject); } }); }
π§ͺ Example:
const p1 = new Promise((res) => setTimeout(() => res("one"), 500)); const p2 = new Promise((res) => setTimeout(() => res("two"), 100)); promiseRace([p1, p2]).then(console.log); // β "two"
β οΈ Example with Rejection:
const p1 = new Promise((_, rej) => setTimeout(() => rej("fail"), 50)); const p2 = new Promise((res) => setTimeout(() => res("win"), 100)); promiseRace([p1, p2]) .then(console.log) .catch(console.error); // β "fail"
Quick Quiz
Test your understanding with 3 quick questions
Q1What determines whether Promise.race resolves or rejects?
Q2What happens when Promise.race is passed an empty array?
Q3Which is a common use case for Promise.race?