Promises.race() in JavaScript
⚡ What is Promise.race()?
Promise.race() returns a promise that settles as soon as any one of the promises in the iterable settles (fulfilled or rejected). The returned promise adopts the state (fulfilled/rejected) and result of the first settled promise.
>>“It’s a race – the first one to settle determines the outcome.”
📦 Syntax
Code Snippet
Promise.race([promise1, promise2, promise3])
.then((value) => {
// First fulfilled value
})
.catch((error) => {
// First rejection reason
});🚀 Example: Competing Promises
Which Promise Wins?
const p1 = new Promise((resolve) => setTimeout(() => resolve("🟢 p1 won"), 1000));
const p2 = new Promise((resolve) => setTimeout(() => resolve("🔵 p2 won"), 500));
const p3 = new Promise((resolve) => setTimeout(() => resolve("🟡 p3 won"), 2000));
Promise.race([p1, p2, p3])
.then((result) => {
console.log(result); // 🔵 p2 won
});Note
🧠 The fastest promise "wins the race" — even if others resolve later, they are ignored.
⛔ Rejection Wins Too
If the first settled promise is rejected, then the entire race is rejected.
First Rejection Wins
const success = new Promise((resolve) => setTimeout(() => resolve("✅ Success"), 1000));
const failure = new Promise((_, reject) => setTimeout(() => reject("❌ Failure"), 500));
Promise.race([success, failure])
.then((res) => console.log("Resolved:", res))
.catch((err) => console.error("Rejected:", err)); // ❌ Failure⏳ Use Case: Timeout Control
Promise.race() is commonly used to implement a timeout for asynchronous operations.
Fetch With Timeout
function fetchWithTimeout(url, timeoutMs) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject("⏰ Request timed out"), timeoutMs)
);
const fetchPromise = fetch(url);
return Promise.race([fetchPromise, timeout]);
}
fetchWithTimeout("https://jsonplaceholder.typicode.com/posts/1", 1000)
.then((res) => res.json())
.then((data) => console.log("Fetched:", data))
.catch((err) => console.error("Error:", err));Note
💡 Useful when you want to reject a long-running async task after a certain time limit.
🧠 Key Points
- Settles based on the first completed promise (resolved or rejected).
- Great for timeout strategies or fallback-first logic.
- Other promises are still running in the background, but are ignored by the returned promise.
📖 More Resources
>>“In a race of promises, the fastest decides the fate.”