Fallback requests
Several equivalent services or mirrors can be queried concurrently; use the first successful response.
JavaScript · Function
Promise.any() returns a promise fulfilled by the first input that fulfills. It rejects with AggregateError when every input rejects, including an empty iterable.
Promise.any() converts the supplied iterable's values to promises and returns a promise that succeeds as soon as one input succeeds. It ignores earlier rejections, but if every input rejects—or the iterable is empty—it rejects with an AggregateError whose errors array contains the rejection reasons in input order.
Promise.any(iterable)| Name | Type | Description |
|---|---|---|
iterable | Iterable | An iterable, such as an Array, containing promise-like values, promises, or ordinary values. |
A Promise that fulfills with the first fulfillment value, or rejects with an AggregateError when all supplied values reject or the iterable is empty.
const slow = new Promise((resolve) => setTimeout(() => resolve("slow"), 50));
const fastFailure = Promise.reject(new Error("temporary failure"));
Promise.any([slow, fastFailure])
.then((value) => console.log(value))
.catch((error) => console.error(error.errors));The rejection does not win: the returned promise fulfills with the value from the first input promise that fulfills.
Several equivalent services or mirrors can be queried concurrently; use the first successful response.
Multiple independent strategies can attempt the same operation, where failures are acceptable until one succeeds.
A group of optional providers can be raced for availability while preserving all failure reasons if none works.
It fulfills with the value of the first input promise to fulfill. Rejections do not settle the result, so an earlier rejection is ignored if another input later succeeds.
Follow-up: How does it differ from Promise.race()? Promise.race() settles on the first fulfillment or rejection, whereas Promise.any() waits through rejections until a fulfillment occurs.
It rejects with an AggregateError when every input rejects, including when the iterable is empty. The error's errors property contains the individual rejection reasons.
Follow-up: How should failure details be inspected? Catch the error and iterate over error.errors, rather than treating the AggregateError itself as the only cause.
The argument is an iterable, such as an array, whose values are awaited; thenables are resolved and non-thenables are used as-is. The returned promise settles asynchronously when rejection or fulfillment is determined.
Follow-up: What ordering applies to collected failures? AggregateError.errors preserves the iterable's input order regardless of completion timing.
Promise.all()Promise.allSettled()Promise.race()AggregateErrorPromise