← 中文资源

简体中文版本

async 函数把 throw 变成 rejection

async 函数恒返回 promise:await 之前 throw 也变成 rejection,由 catch 接住;普通函数的 throw 是同步异常,必须 try/catch。

阅读英文原文

运行结果

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

plain needs try: sync throw
caught: sync-looking throw
early: missing flag
ok: ready

实现说明

async 函数把 throw 变成 rejection可以归结为函数 boom、earlyExit、plain。 异步部分依次 await 结果,顺序可预测。代码拒绝在坏状态上继续,在守卫处直接抛出 Error。

使用要点

  • 守卫 !flag 命中后立刻用提前的 throw 结束这一轮。
  • 演示输出是带标签的(caught:、early:、ok:),每个操作都会留下自己的一行标注。

常见问题

这个示例会以什么方式失败?

守卫处(!flag)会抛出 Error,非法状态到不了主逻辑。

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 boom、earlyExit、plain。

主要签名是 async function boom()

核心语句

if (!flag) throw new Error('missing flag');
throw new Error('sync-looking throw');
throw new Error('sync throw');

代码示例

// async 函数永远返回 promise:同步 throw 也会变成 rejection
async function boom() {
  throw new Error('sync-looking throw');
}

boom().catch((err) => console.log('caught:', err.message));

// throw 发生在任何 await 之前也一样:调用方拿到的仍是 rejected promise
async function earlyExit(flag) {
  if (!flag) throw new Error('missing flag');
  return 'ready';
}

earlyExit(false).catch((err) => console.log('early:', err.message));
earlyExit(true).then((v) => console.log('ok:', v));

// 非 async 普通函数的 throw 是同步异常,必须 try/catch 接住
function plain() {
  throw new Error('sync throw');
}
try {
  plain();
} catch (err) {
  console.log('plain needs try:', err.message);
}