JavaScript Intermediate
What is Promise.race()? How do you implement it?
What is Promise.race()?
Promise.race(iterable) takes an iterable of Promises and returns a new Promise that settles with the first Promise to settle — whether fulfilled or rejected.
Basic Usage
const p1 = new Promise(resolve => setTimeout(() => resolve('p1'), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve('p2'), 500));
const p3 = new Promise((_, reject) => setTimeout(() => reject('p3 error'), 300));
Promise.race([p1, p2, p3])
.then(result => console.log(result)) // won't execute
.catch(err => console.error(err)); // 'p3 error' (p3 is fastest and rejected)
Practical Use: Timeout Mechanism
This is the most common use case for Promise.race():
function timeout(ms) {
return new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), ms)
);
}
function fetchWithTimeout(url, ms) {
return Promise.race([
fetch(url),
timeout(ms)
]);
}
fetchWithTimeout('/api/data', 3000)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err.message)); // If timed out: 'Request timed out'
Implementing Promise.race()
function myPromiseRace(promises) {
return new Promise((resolve, reject) => {
for (const promise of promises) {
Promise.resolve(promise).then(resolve, reject);
}
});
}
Notes
Promise.race()only cares about the first to settle; remaining Promises still execute but their results are ignored- If given an empty array, the returned Promise will remain pending forever
- Difference from
Promise.any():racesettles on first (success or failure),anywaits for the first success
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
