Introduction
JavaScript Promise.race() method is a static method of the built-in Promise object. It accepts an iterable of Promises and returns a new Promise that settles as soon as the first input Promise settles. The first result may be a fulfilled value or a rejection reason, so Promise.race() is useful when an application needs to respond to whichever asynchronous operation finishes first.
For example, a web application may request data from a server but should stop waiting after a fixed time. You can race the network request against a timeout Promise. You can also compare multiple data sources, monitor competing operations, or select the first completed task. This tutorial explains the syntax, behavior, practical examples, error handling, and differences between JavaScript Promise concurrency methods.
JavaScript Promise.race() Syntax
Promise.race(iterable);
- iterable: An iterable object, usually an array, containing Promises or values.
- Return value: A new Promise that adopts the outcome of the first input to settle.
The iterable can contain already-created Promises, Promises created by asynchronous functions, or non-Promise values. Ordinary values are treated like already-fulfilled Promises for the race.
Basic Example of Promise.race()
The following example creates three Promises with different completion times. The Promise with the shortest timer settles first.
const firstTask = new Promise((resolve) => {
setTimeout(() => resolve("First task completed"), 1000);
});
const secondTask = new Promise((resolve) => {
setTimeout(() => resolve("Second task completed"), 2000);
});
const thirdTask = new Promise((resolve) => {
setTimeout(() => resolve("Third task completed"), 3000);
});
Promise.race([firstTask, secondTask, thirdTask])
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
Output:
First task completed
The first task resolves after one second, so the returned Promise fulfills with its value. The second and third timers are not automatically stopped; they still run and settle their own Promises.
How Promise.race() Works
When Promise.race() receives an iterable, JavaScript obtains the values from that iterable and observes their settlement. The first input to fulfill or reject determines the result of the Promise returned by Promise.race().
- Pass an iterable containing Promises or values to
Promise.race(). - The method returns a new Promise.
- Each input is observed for fulfillment or rejection.
- The first input that settles determines the returned Promise’s outcome.
- Later settlements do not change the already-settled returned Promise.
The race is based on settlement order, not on the order of elements in the array. An input listed first does not automatically win.
Promise.race() with Different Execution Times
This example makes the completion order easier to see by logging each task separately.
function createTask(name, delay) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(name, "finished");
resolve(name);
}, delay);
});
}
const taskA = createTask("Task A", 2500);
const taskB = createTask("Task B", 700);
const taskC = createTask("Task C", 1500);
Promise.race([taskA, taskB, taskC])
.then((winner) => console.log("Race winner:", winner));
Possible output:
Task B finished
Race winner: Task B
Task C finished
Task A finished
Task B wins because it settles first. The other timers continue and their own callbacks still execute. This demonstrates why racing Promises is not the same as cancelling losing tasks.
Promise.race() with a Timeout
One common use case is setting a maximum waiting time for an asynchronous operation. You can create a timeout Promise that rejects after a specified duration, then race it against the operation.
function timeoutAfter(milliseconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("The operation timed out"));
}, milliseconds);
});
}
const request = fetch("https://jsonplaceholder.typicode.com/posts/1");
Promise.race([request, timeoutAfter(3000)])
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error: " + response.status);
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(error.message));
If the fetch request settles before three seconds, its response wins. If the timeout rejects first, the race rejects with the timeout error. However, the fetch request itself continues in the background. A timeout race alone does not abort the network request.
Combining Promise.race() with AbortController
To stop a fetch request after a timeout, use AbortController. The controller can abort the request, while a timer triggers the abort operation.
async function fetchWithTimeout(url, milliseconds) {
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, milliseconds);
try {
const response = await fetch(url, {
signal: controller.signal
});
if (!response.ok) {
throw new Error("HTTP error: " + response.status);
}
return await response.json();
} finally {
clearTimeout(timer);
}
}
fetchWithTimeout(
"https://jsonplaceholder.typicode.com/posts/1",
3000
)
.then((data) => console.log(data))
.catch((error) => console.error(error.name, error.message));
This version uses cancellation rather than relying on a race alone. When the timer fires, controller.abort() signals fetch to stop. The finally block clears the timer when the request finishes earlier.
Promise.race() with Rejected Promises
The first Promise to reject can win the race. A successful Promise that settles later cannot change the returned Promise’s rejected state.
const fastFailure = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Server unavailable")), 500);
});
const slowSuccess = new Promise((resolve) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
Promise.race([fastFailure, slowSuccess])
.then((result) => console.log(result))
.catch((error) => console.log(error.message));
Output:
Server unavailable
Use catch() to handle a rejected race. If your application should wait for the first successful result while ignoring earlier failures, Promise.race() is not the right method; consider Promise.any().
Promise.race() with Ordinary Values
An iterable may contain values that are not Promises. JavaScript treats each ordinary value as an already-fulfilled Promise during the race.
const delayedValue = new Promise((resolve) => {
setTimeout(() => resolve("Delayed result"), 1000);
});
Promise.race([delayedValue, "Immediate value"])
.then((result) => console.log(result));
Output:
Immediate value
The ordinary value is processed as an already-fulfilled input, so it generally settles the race before a Promise that resolves asynchronously. When multiple inputs are already settled, the reactions are still processed through the Promise job queue.
Promise.race() with an Empty Array
If the iterable is empty, Promise.race() returns a Promise that remains pending forever. There is no input that can fulfill or reject it.
const result = Promise.race([]);
result.then(() => {
console.log("This will not run");
});
console.log("The race is still pending");
Output:
The race is still pending
Check that an array contains at least one task when your program expects the race to complete.
Using Promise.race() with Async Functions
An async function always returns a Promise. This makes async functions convenient inputs for Promise.race().
async function getLocalData() {
await new Promise((resolve) => setTimeout(resolve, 800));
return "Local data";
}
async function getRemoteData() {
await new Promise((resolve) => setTimeout(resolve, 1200));
return "Remote data";
}
Promise.race([getLocalData(), getRemoteData()])
.then((result) => console.log(result));
Output:
Local data
Both functions begin when they are called. The race returns the first settled result, which is the local data in this example.
Promise.race() vs Promise.all()
Promise.race() and Promise.all() both accept iterables, but they solve different problems.
| Feature | Promise.race() | Promise.all() |
|---|---|---|
| Completion condition | First input to settle | All inputs fulfill |
| Fulfillment value | First settled input’s value | Array of fulfillment values in input order |
| Rejection | Rejects if the first settled input rejects | Rejects when an input rejects |
| Empty iterable | Remains pending | Fulfills with an empty array |
| Typical use | Timeouts and competing tasks | Waiting for all independent tasks |
Use Promise.all() when every operation must succeed before continuing, such as loading several sections of a dashboard. Use Promise.race() when the first settlement should determine the immediate outcome.
Promise.race() vs Promise.any()
These methods are easy to confuse because both can return before every input has settled. Their rejection behavior is different.
Promise.race()adopts the first fulfilled or rejected outcome.Promise.any()fulfills with the first fulfilled input and ignores rejections while waiting for a success.Promise.any()rejects with anAggregateErroronly when all inputs reject.
const tasks = [
Promise.reject("First task failed"),
new Promise((resolve) => {
setTimeout(() => resolve("Second task succeeded"), 500);
})
];
Promise.any(tasks)
.then((result) => console.log(result))
.catch((error) => console.error(error));
This example fulfills with the second task’s value. By contrast, Promise.race(tasks) would reject with the first task’s rejection because it settles first.
Practical Example: Selecting the Fastest API Response
An application may have two equivalent API endpoints or data providers. You can start both requests and use the first response that settles. Remember that if the first response is an error, the race rejects rather than waiting for the other request to succeed.
const primaryRequest = fetch("/api/primary-data");
const backupRequest = fetch("/api/backup-data");
Promise.race([primaryRequest, backupRequest])
.then((response) => {
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
return response.json();
})
.then((data) => {
console.log("First response:", data);
})
.catch((error) => {
console.error("The first settled request failed:", error);
});
This example chooses the first response to settle, not necessarily the first valid response. If you need the first successful response, use Promise.any() with request Promises that reject for unsuccessful HTTP status codes.
Handling HTTP Errors Before Racing Requests
The Fetch API normally fulfills its Promise even when the server responds with an HTTP error such as 404 or 500. To make an unsuccessful HTTP response count as a rejected task, validate response.ok inside each request Promise.
async function requestJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
}
Promise.race([
requestJson("/api/primary"),
requestJson("/api/backup")
])
.then((data) => console.log(data))
.catch((error) => console.error(error.message));
Now a request that returns an unsuccessful HTTP status rejects. Since this is still Promise.race(), the first rejection can determine the result even if another request later succeeds.
Important Behavior to Understand
- First settlement wins: The winner can fulfill or reject.
- No automatic cancellation: Other operations continue unless explicitly cancelled.
- Input order is not priority: The fastest settlement determines the result, not the first array position.
- Empty input stays pending: An empty iterable provides no Promise to settle the race.
- Values are accepted: Non-Promise values are treated as fulfilled inputs.
- Errors need handling: Attach
catch()or usetry...catchwithawait.
Using Promise.race() with async and await
You can use await with the Promise returned by Promise.race(). This often makes asynchronous code easier to read.
async function runRace() {
const taskOne = new Promise((resolve) => {
setTimeout(() => resolve("Task one"), 1000);
});
const taskTwo = new Promise((resolve) => {
setTimeout(() => resolve("Task two"), 600);
});
try {
const winner = await Promise.race([taskOne, taskTwo]);
console.log(winner);
} catch (error) {
console.error("Race failed:", error);
}
}
runRace();
The async function pauses at await until the race settles. If the winning input rejects, execution moves to the catch block.
When to Use Promise.race()
Promise.race() is useful when the first completed outcome should control what happens next. Typical scenarios include:
- Creating a timeout outcome for a long-running operation.
- Comparing the response time of multiple services.
- Choosing the first completed computation when any outcome is acceptable.
- Monitoring competing asynchronous tasks.
- Building responsive interfaces that need a quick result or an early error.
Choose the method based on the behavior your application needs. Use Promise.race() for the first settlement, Promise.any() for the first fulfillment, Promise.all() when all inputs must fulfill, and Promise.allSettled() when you need the outcome of every input regardless of success or failure.