Promise.any Aggregates All Rejection Causes
Promise.any settles with the first fulfilled attempt and only throws AggregateError when every input rejects, keeping each original cause in errors.
Code
// Promise.any aggregates the causes of every rejection.
async function probe(name: string, fail: boolean): Promise<string> {
if (fail) throw new Error(name + " failed");
return name + " ok";
}
async function main(): Promise<void> {
// One healthy replica among three probes: any resolves with the first success.
const winner = await Promise.any([
probe("primary", true),
probe("replica", true),
probe("cache", false),
]);
console.log("winner:", winner);
// Every input rejected: AggregateError.errors keeps each cause in submission order.
try {
await Promise.any([probe("a", true), probe("b", true)]);
} catch (error: unknown) {
if (error instanceof AggregateError) {
console.log("rejected:", error.errors.map((e) => e.message).join("; "));
}
}
}
await main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
winner: cache ok
rejected: a failed; b failedHow the snippet works
probe and main are the two functions; Promise.any aggregates the rest of the story.
Every asynchronous step is awaited, so rejections surface where the call happens. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Points of care
- Built-in APIs only, so there is no supply chain to vet.
- The guard
failshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
The primary signature is async function probe(name: string, fail: boolean)
Running the file prints labeled results such as winner:, rejected: — the first success and the aggregate rejection each get a line.
Running the file executes main, which drives probe in order.
Key statements
await Promise.any([probe("a", true), probe("b", true)]);
const winner = await Promise.any([
probe("primary", true),
probe("replica", true),
probe("cache", false),
]);
async function probe(name: string, fail: boolean): Promise<string> {
if (fail) throw new Error(name + " failed");
return name + " ok";
}
Interactive Tools for This Topic
FAQ
- What happens if the preconditions do not hold?
- It throws `Error` before any real work runs, via the guard `fail` — handle it at the call site or let it propagate deliberately.
- What does Promise.any Aggregates All Rejection Causes print when run?
- No setup needed: run the file and look for labeled lines like `winner:`, `rejected:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.