Promise.race: The First to Settle
What You'll Learn
You'll learn how Promise.race() resolves or rejects based on whichever promise in an array settles first—whether that's a success or failure.
The Core Idea
While Promise.all() waits for every promise to succeed (or any to fail), Promise.race() takes a different approach: it settles as soon as any single promise in the array settles, adopting that promise's outcome.
Think of it like a race with multiple runners. The moment the first runner crosses the finish line, the race is over—you don't wait for anyone else. That first finisher determines the result, whether they won fair and square (resolved) or tripped and fell (rejected).
How Promise.race Works
const promise1 = new Promise(resolve => setTimeout(() => resolve('slow'), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve('fast'), 100));
Promise.race([promise1, promise2])
.then(result => console.log(result)); // Logs: 'fast'
The first promise to settle "wins" the race. Here, promise2 resolves after 100ms, so the entire race resolves with 'fast'.
Rejection in a Race
If the first promise to settle is a rejection, the race rejects:
const promise1 = new Promise((_, reject) => setTimeout(() => reject('error!'), 50));
const promise2 = new Promise(resolve => setTimeout(() => resolve('success'), 100));
Promise.race([promise1, promise2])
.catch(error => console.log(error)); // Logs: 'error!'
The rejection happens first, so Promise.race() rejects—even though another promise would have succeeded later.
Use Cases
Promise.race() is perfect for timeout patterns: race your actual operation against a timeout promise, and if the timeout wins, you know the operation took too long.
Key Takeaway: Promise.race() settles immediately when the first promise in its array settles, adopting that promise's resolved value or rejection reason—it's first past the post wins.