← 中文资源

简体中文版本

Promise.any 聚合全部拒绝原因

Promise.any 以第一个 fulfilled 结算,只有全部输入拒绝时才抛 AggregateError;errors 数组按提交顺序保留每个原始错误。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

winner: cache ok
rejected: a failed; b failed

实现说明

起作用的部分是函数 probe、main。 异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。代码不会带着坏状态静默继续,守卫一命中就抛 Error。

使用要点

  • 守卫 fail 命中后立刻用提前的 throw 结束这一轮。
  • 每一步打印都带着自己的标签:winner:、rejected:。
  • main 的演示流程是 probe——跑一遍文件,这条流程从头到尾可见。

常见问题

前置条件不成立会发生什么?

在真正开工之前就会抛出 Error(守卫:fail)——请在调用点处理,或有意向上传播。

运行「Promise.any 聚合全部拒绝原因」会打印什么?

运行文件本身,winner:、rejected: 这些前缀各对应一段演示逻辑。

主签名形如 async function probe(name: string, fail: boolean)

核心语句

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";
}

代码示例

// 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();