← 中文资源

简体中文版本

allSettled 部分失败处理

批次不能整体失败时用 allSettled:全部落地后按 fulfilled/rejected 分流,单点失败不连坐。

阅读英文原文

运行结果

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

ok: 4 failed: 2
[
  { id: 3, reason: 'upstream 500 for 3' },
  { id: 6, reason: 'upstream 500 for 6' }
]

实现说明

整个示例围绕函数 fetchOne、collect组织。 异步部分依次 await 结果,顺序可预测。代码不会带着坏状态静默继续,守卫一命中就抛 Error。 返回值是携带 id 的对象。

使用要点

  • 守卫 id % 3 === 0 一旦成立就走提前的 throw,把后续流程挡掉。
  • 直接运行文件,输出会带上标签,比如 ok:——输出的每一行都能指回产生它的那次调用。

常见问题

fetchOne 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

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

代码会抛出 Error——守卫条件 id % 3 === 0 会在主逻辑之前拦下坏状态。请在调用点处理,或有意让它向上传播。

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 文件在加载时定义 fetchOne、collect。

主要签名是 async function fetchOne(id)

核心语句

const results = await Promise.allSettled(ids.map(fetchOne));
collect([1, 2, 3, 4, 5, 6]).then((summary) => {
  console.log('ok:', summary.ok.length, 'failed:', summary.failed.length);
  console.log(summary.failed);
});
if (id % 3 === 0) throw new Error('upstream 500 for ' + id);

代码示例

async function fetchOne(id) {
  if (id % 3 === 0) throw new Error('upstream 500 for ' + id);
  return { id, value: id * 10 };
}

async function collect(ids) {
  // allSettled:始终等到全部落地,单点失败不连坐
  const results = await Promise.allSettled(ids.map(fetchOne));

  const ok = [];
  const failed = [];
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') ok.push(result.value);
    else failed.push({ id: ids[index], reason: result.reason.message });
  });

  return { ok, failed };
}

collect([1, 2, 3, 4, 5, 6]).then((summary) => {
  console.log('ok:', summary.ok.length, 'failed:', summary.failed.length);
  console.log(summary.failed);
});