Timeout asynchronous work
Use a task together with a rejecting delay to enforce a maximum response time.
JavaScript · Function
Promise.race() returns a promise whose outcome follows the first item in an iterable to settle, whether fulfillment or rejection. It always settles asynchronously and remains pending when given an empty iterable.
Promise.race() converts each item in an iterable into a promise and returns a new promise whose outcome follows whichever item settles first. The outcome may be fulfillment or rejection, and settlement is always asynchronous—even for an empty iterable or an iterable containing only already-settled values.
Promise.race(iterable)| Name | Type | Description |
|---|---|---|
iterable | iterable | An iterable, such as an Array, containing promises, thenables, or other values to race. |
A Promise that asynchronously settles with the eventual state of the first item in the iterable to settle; it fulfills with that item's value or rejects with its reason.
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timed out")), 1000),
);
const result = await Promise.race([
fetch("/api/data").then((response) => response.json()),
timeout,
]);
console.log(result);The first operation to settle determines whether the race fulfills or rejects.
Use a task together with a rejecting delay to enforce a maximum response time.
Start equivalent asynchronous operations and accept whichever responds first.
Select among values or promises where the earliest settled candidate should determine the outcome.
It returns a promise that follows the first promise or value in the iterable to settle. A fulfillment produces fulfillment with that value, while a rejection produces rejection with its reason.
Follow-up: What happens with an empty iterable? The returned promise remains pending forever, so neither fulfillment nor rejection occurs.
The method accepts an iterable, such as an array, whose entries can be promises, thenables, or ordinary values. Thenables are resolved, while non-thenables are used as values.
Follow-up: How can an ordinary value win? If it appears before an already-settled promise or other non-pending winner in iteration order, it can determine the result.
Promise.race() always settles asynchronously. This remains true even when the iterable is non-empty and contains no pending promises, or when the iterable is empty.
Follow-up: Why does the empty case differ from the other cases? It stays pending forever because there is no item capable of settling the race.
Promise.all()Promise.allSettled()Promise.any()Promise.prototype.then()