Loading article...
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.
Promise.race returns a promise that settles as soon as any input promise settles β resolved or rejected.
First one wins β race ends immediately.
Promise.resolve() to normalize non-promises.then(resolve) and .catch(reject) to each inputpromiseRacefunction promiseRace(iterable) { return new Promise((resolve, reject) => { for (const item of iterable) { Promise.resolve(item) .then(resolve) .catch(reject); } }); }
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"
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"
Test your understanding with 3 quick questions