Promise.any Short-Circuits To First Success

Resolve with the first fulfilled task using Promise.any, and collect every rejection cause in AggregateError.errors only when all tasks fail.

JavascriptResilience

Code

javascriptsnippet
20 lines
// Promise.any: 任一 fulfilled 即短路;全部失败才抛 AggregateError
const probe = (name, ms, fail) =>
  new Promise((resolve, reject) =>
    setTimeout(() => (fail ? reject(new Error(`${name} failed`)) : resolve(`${name} ok`)), ms));

// 最快的成功者获胜:mirror 10ms 先于 primary 40ms
const fastest = await Promise.any([
  probe('primary', 40, true),
  probe('mirror', 10, false),
  probe('backup', 30, false),
]);
console.log('winner:', fastest);

// 全部失败:AggregateError.errors 收齐每个 reject 原因
try {
  await Promise.any([probe('a', 10, true), probe('b', 20, true)]);
} catch (error) {
  console.log('instanceof AggregateError:', error instanceof AggregateError);
  console.log(error.errors.map((e) => e.message).join(' | '));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

winner: mirror ok
instanceof AggregateError: true
a failed | b failed

How the snippet works

Count the function probe as the entire surface area of Promise.any Short-Circuits To First Success.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Using it

Signature: const probe = (name, ms, fail)

Running the file prints labeled results such as winner:, instanceof AggregateError: — each operation’s effect is visible in the output.

Key statements

await Promise.any([probe('a', 10, true), probe('b', 20, true)]);
const fastest = await Promise.any([
probe('primary', 40, true),
probe('mirror', 10, false),
probe('backup', 30, false),
]);
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(`${name} failed`)) : resolve(`${name} ok`)), ms));

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `probe` at load time.