← 中文资源

简体中文版本

async 函数永远返回 Promise

async 把普通返回值包成 Promise、收编 thenable、把 throw 变成 rejection:await 两侧看到的始终是同一个最终值。

阅读英文原文

运行结果

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

is promise: true
wrapped: 42
rejected: resolver offline
adopted: adopted
awaited: 42 adopted

实现说明

async 函数永远返回 Promise以函数 plainReturn、passThrough、fails、main为骨架。 await 标出每个异步边界——没有 fire-and-forget。Error 在其所在位置无条件抛出——前面没有任何输入检查。

使用要点

  • 演示输出是带标签的(is promise:、wrapped:、adopted:),每个操作都会留下自己的一行标注。
  • main 的演示流程是 plainReturn、passThrough——跑一遍文件,这条流程从头到尾可见。

常见问题

异常是由什么触发的?

不会。Error 不在任何守卫之后——只要执行到那行代码就会触发。

运行「async 函数永远返回 Promise」会打印什么?

整个文件跑完,输出行以 is promise:、wrapped:、adopted: 这类前缀开头。

主要签名是 async function plainReturn()

核心语句

return Promise.resolve('adopted');
throw new Error('resolver offline');
const a = await plainReturn();

代码示例

// async 函数永远返回 Promise:普通值被包装,thenable 被收编
async function plainReturn() {
  return 42;
}

async function passThrough() {
  return Promise.resolve('adopted');
}

async function fails() {
  throw new Error('resolver offline');
}

console.log('is promise:', plainReturn() instanceof Promise);

plainReturn().then((value) => console.log('wrapped:', value));
passThrough().then((value) => console.log('adopted:', value));
fails().catch((error) => console.log('rejected:', error.message));

// await 两侧看到的是同一个最终值:包装差异被 await 抹平
async function main() {
  const a = await plainReturn();
  const b = await passThrough();
  console.log('awaited:', a, b);
}

main();