← 中文资源

简体中文版本

promise 链的错误传播与单点捕获

链上任何一步抛错都会跳过后续 then、把 rejection 传到最近的 catch:一个处理器兜住整条链,catch 里返回普通值链就恢复 fulfilled 继续执行。

阅读英文原文

运行结果

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

charge 200 cents
failed: SyntaxError
recovered from BOOM

实现说明

await 点把异步工作排成序列,拒绝落在取结果的那一行。 各个操作都建立在顶层绑定之上:ok、failed、recovered。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件的状态由几个模块级绑定持有:ok、failed、recovered。

核心语句

.then((message) => `recovered from ${message}`);
const ok = await Promise.resolve('{"qty":2}')
  .then((text) => JSON.parse(text))
  .then((data) => data.qty * 100)
  .then((cents) => `charge ${cents} cents`);
.catch((error) => `failed: ${error.name}`);

代码示例

// 链上任何一步抛错:后续 then 全部跳过,rejection 沿链传到最近的 catch
const ok = await Promise.resolve('{"qty":2}')
  .then((text) => JSON.parse(text))
  .then((data) => data.qty * 100)
  .then((cents) => `charge ${cents} cents`);
console.log(ok);

// JSON.parse 抛出的 SyntaxError 被链尾的 catch 接住,中间步骤不再执行
const failed = await Promise.resolve('not-json')
  .then((text) => JSON.parse(text))
  .then((data) => data.qty * 100)
  .then((cents) => `charge ${cents} cents`)
  .catch((error) => `failed: ${error.name}`);
console.log(failed);

// catch 返回普通值即恢复 fulfilled,链可以继续走下去
const recovered = await Promise.reject(new Error('boom'))
  .catch((error) => error.message.toUpperCase())
  .then((message) => `recovered from ${message}`);
console.log(recovered);