Promise.race with Empty Arrays
You'll learn what happens when you call Promise.race() with an empty array—and why it behaves differently from Promise.all().
The Surprising Behavior
When you pass an empty array to Promise.race(), it returns a promise that never settles. It won't resolve, it won't reject—it simply hangs forever in a pending state.
const emptyRace = Promise.race([]);
emptyRace.then(() => {
console.log('This will never run');
});
emptyRace.catch(() => {
console.log('This will also never run');
});
console.log('This runs immediately');
// Output: "This runs immediately"
// (then nothing else ever happens)
Why This Happens
Think of Promise.race() like a footrace: the first runner to cross the finish line determines the winner. But what if there are no runners in the race? The race can never finish—there's no one to declare a winner!
Since Promise.race() settles with the first promise that settles, and there are no promises to race, it has nothing to settle with. The promise remains pending indefinitely.
Contrast with Promise.all
Remember that Promise.all([]) returns a promise that immediately resolves with an empty array. That's because "all" of zero promises have succeeded (vacuously true). But Promise.race([]) can't pick a "first" from an empty set.
Practical Implications
This behavior is rarely useful and usually indicates a bug. Always ensure your array contains at least one promise before racing, or handle the empty case explicitly:
const promises = getSomePromises(); // might be empty
if (promises.length === 0) {
// Handle the empty case yourself
console.log('No promises to race');
} else {
Promise.race(promises).then(result => console.log(result));
}
Key Takeaway: Promise.race([]) returns a promise that never settles because there's no "first" promise to determine the race outcome.