AggregateError Collects Every Rejection
Promise.any settles with the first success; when every attempt rejects it throws AggregateError carrying each member error for inspection.
Code
const attempt = (name, ok) =>
ok ? Promise.resolve(name + ': ok') : Promise.reject(new Error(name + ' failed'));
// Promise.any 等第一个成功;全部失败时抛 AggregateError,errors 保留每个原因
const mirrors = [
attempt('mirror-a', false),
attempt('mirror-b', false),
attempt('mirror-c', false),
];
try {
await Promise.any(mirrors);
} catch (aggregate) {
console.log(aggregate.name);
for (const err of aggregate.errors) {
console.log('member:', err.message);
}
}
// 任一镜像可用即成功:AggregateError 只在“全败”时出现
const mixed = [attempt('mirror-a', false), attempt('mirror-c', true)];
console.log('any success:', await Promise.any(mixed));Output
Captured from a sandboxed run of this snippet in the build pipeline.
AggregateError
member: mirror-a failed
member: mirror-b failed
member: mirror-c failed
any success: mirror-c: okInside the snippet
AggregateError Collects Every Rejection comes down to the function attempt.
The cycling part of this snippet is for (const err of aggregate.errors). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Caveats
- The environment needs no preparation beyond having the interpreter or compiler.
Using it
The functional core is declared as const attempt = (name, ok)
The demo output is labeled (member:, any success:), with the printed labels following the code’s order.
Key statements
await Promise.any(mirrors);
ok ? Promise.resolve(name + ': ok') : Promise.reject(new Error(name + ' failed'));
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `attempt` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.