Promise.race() is a method that returns a promise as soon as any of the promises in an iterable (like an array) settles—whether it resolves or rejects.
Think of it as a literal race: the first promise to cross the finish line wins, and its result (or error) is the only one that matters.
1. How it Works
Promise.race() settles as soon as the fastest promise settles.
- If the fastest promise fulfills: The returned promise fulfills with that value.
- If the fastest promise rejects: The returned promise rejects with that reason.
2. Basic Example
In this example, task2 is the fastest, so its value is the one that gets logged.
const task1 = new Promise((resolve) => setTimeout(() => resolve("Task 1 finished"), 3000));
const task2 = new Promise((resolve) => setTimeout(() => resolve("Task 2 finished"), 1000));
const task3 = new Promise((resolve) => setTimeout(() => resolve("Task 3 finished"), 2000));
Promise.race([task1, task2, task3])
.then((value) => {
console.log(value); // Logs: "Task 2 finished"
})
.catch((error) => {
console.error(error);
});
3. Real-World Use Case: Timing Out an API Call
The most common use for Promise.race() is to stop waiting for a network request if it takes too long. You race your actual request against a “timeout” promise.
const request = fetch("https://api.example.com/data");
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Request timed out!")), 5000)
);
Promise.race([request, timeout])
.then((response) => {
console.log("Data received:", response);
})
.catch((error) => {
console.error(error.message); // Logs "Request timed out!" if fetch takes > 5s
});
4. Rejection in a Race
If the fastest promise is a rejection, Promise.race() will reject, even if there are other promises in the array that would have eventually succeeded.
const fastFailure = new Promise((_, reject) => setTimeout(() => reject("I failed fast!"), 500));
const slowSuccess = new Promise((resolve) => setTimeout(() => resolve("I am slow but steady"), 2000));
Promise.race([fastFailure, slowSuccess])
.then(val => console.log(val))
.catch(err => console.log(err)); // Logs: "I failed fast!"
