← 中文资源

简体中文版本

allSettled 按状态收窄结果类型

Promise.allSettled 不会整体 reject:每个结果带 status 判别字段,fulfilled 分支拿到 value,rejected 分支的 reason 是 unknown。

阅读英文原文

运行结果

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

ok: 21
failed: station offline
ok: 21

实现说明

allSettled 按状态收窄结果类型以函数 load、main为骨架。 这个示例中仅有的重复出现在 for (const result of settled) 里。异步流被 await 线性化,失败处理保持局部。

使用要点

  • 跑完文件,输出里会留下标记——ok:、failed:。
  • 运行整个文件:main 会依次驱动 load。

常见问题

运行「allSettled 按状态收窄结果类型」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 ok:、failed: 标签标明各步骤。

主要签名是 const load = (id: string)

核心语句

const settled = await Promise.allSettled([load('a'), load('bad'), load('c')]);
id === 'bad' ? Promise.reject(new Error('station offline')) : Promise.resolve({ celsius: 21 });

代码示例

type Weather = { celsius: number };

const load = (id: string): Promise<Weather> =>
  id === 'bad' ? Promise.reject(new Error('station offline')) : Promise.resolve({ celsius: 21 });

// allSettled 不会整体 reject:每个结果都带 status 判别字段
async function main() {
  const settled = await Promise.allSettled([load('a'), load('bad'), load('c')]);

  for (const result of settled) {
    if (result.status === 'fulfilled') {
      // 收窄为 PromiseFulfilledResult<Weather>:value 可用
      console.log('ok:', result.value.celsius);
    } else {
      // 收窄为 PromiseRejectedResult:reason 是 unknown
      console.log(
        'failed:',
        result.reason instanceof Error ? result.reason.message : String(result.reason),
      );
    }
  }
}

main();