Glossary / Promise.any
Promise.any
Promise.any(iterable) fulfills with the first input that fulfills, ignoring earlier rejections. If every input rejects, it rejects with an AggregateError containing the rejection reasons. It is appropriate when any successful replica or alternative is sufficient; it differs from Promise.race, which settles on the first fulfillment or rejection.
First-success policy
const data = await Promise.any([
fetchFromPrimary(),
fetchFromReplica(),
]);
If one source rejects quickly and another later fulfills, Promise.any fulfills with the latter. If all reject, inspect error.errors for per-source causes. An empty iterable rejects with an AggregateError because no input can fulfill. Promise.any does not cancel remaining work when one fulfills, so abort losing requests if resource conservation matters and the underlying API supports cancellation.
Be careful with hedged requests: starting multiple replicas can increase load. Add a delay before launching backup work, cap concurrency, and define which result is authoritative. Never assume the first successful response is newest or consistent without a data contract.
Interview questions
- How does any differ from race? Any waits for first fulfillment; race settles on first settlement of either kind.
- What if every input rejects? AggregateError with individual reasons.
- Does any cancel pending inputs after success? No.
- When is it useful? Replicas/fallbacks where any valid success is sufficient.