JavaScript Reference ยท Promises and Async
Promise.any()
Reference for Promise.any(): fulfill with the first successful promise, ignore earlier failures, and handle AggregateError when every promise rejects.
Promise.any() returns a promise that fulfills with the value of the first input promise to fulfill. Rejections are ignored as long as at least one input can still succeed. Only when all inputs reject does the result reject, with an AggregateError that collects every reason.
It suits "ask several sources and take the first good answer", such as trying mirror servers.
const data = await Promise.any([fromMirrorA(), fromMirrorB()]);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Promise.any(iterable)
| Name | Description |
|---|---|
iterable |
An iterable of promises or plain values. |
Return value: a promise that fulfills with the first fulfillment value. If every input rejects, or the iterable is empty, it rejects with an AggregateError. The error's errors property is an array of the rejection reasons in input order.
Exceptions: if the argument is not iterable, the returned promise rejects with a TypeError.
Usage notes
- Failures are tolerated. Individual rejections are swallowed while another input might still fulfill.
- Empty input rejects. Unlike
Promise.race(), an empty list does not hang; it rejects with anAggregateErrorwhoseerrorsis empty. errorsfollow input order, not the order in which the promises failed.- Other tasks are not cancelled. Combine with an
AbortControllerto stop the slower requests once one has won. - Compare:
Promise.race()copies the first outcome of any kind,Promise.all()needs every success,Promise.allSettled()never rejects. - Plain values are treated as already fulfilled, so one among the inputs ends the race at once.
Browser support
Supported in current versions of all major browsers and Node.js; it is newer than Promise.all() and Promise.race(), so check a compatibility table for older environments.