async/await 和 Promise 有什么关系?
参考答案
关系
async/await 是 Promise 的语法糖(更准确说:基于 Promise + Generator 的语法封装)。async 函数总是返回一个 Promise,await 用于等待一个 Promise 落定并取值。
对应关系
// async/await
async function f() {
const a = await p1;
return a + 1;
}
// 等价的 Promise 写法
function f() {
return p1.then(a => a + 1);
}
具体关联
- **
async函数返回 Promise**:return的值会被Promise.resolve包装;抛出异常会变成 rejected Promise。
async function a() { return 1; }
a() instanceof Promise; // true
- **
await等价于.then**:await p会等待p落定,成功取值、失败抛异常(由try/catch捕获,等价于.catch)。 - 错误处理映射:
try/catch↔.catch;finally↔.finally。 - **
await只对 thenable 生效**:对普通值直接返回;对非 Promise 值会Promise.resolve包装。 - 本质实现:
async/await可视为"带内置执行器的 Generator"——await类似yield,引擎负责等待 Promise 落定后恢复执行(co 库就是手写这套逻辑)。
差异
| 维度 | Promise | async/await |
| --- | --- | --- |
| 写法 | 链式 .then | 同步式顺序代码 |
| 可读性 | 长链较难读 | 接近同步、直观 |
| 错误处理 | .catch | try/catch(更符合直觉) |
| 调试 | 调用栈不连续 | 调用栈更连续(更好断点) |
| 并行 | Promise.all | 也需 Promise.all(否则串行) |
| 条件/循环 | 需嵌套或递归 | 直接用 if/for |
| 本质 | 底层原语 | Promise 的语法糖 |
容易踩的坑
// ❌ 串行:多等了一个
const a = await getA();
const b = await getB(); // 本可并行
// ✅ 并行
const [a, b] = await Promise.all([getA(), getB()]);
// ❌ 在 forEach 里 await 不会等待
arr.forEach(async (x) => { await f(x); });
// ✅ 用 for...of 或 Promise.all
for (const x of arr) await f(x);
await Promise.all(arr.map(f));
结论
**async/await 不替代 Promise,而是让 Promise 更好用**:底层仍是 Promise 的微任务与状态机;需要并行、竞速、批量容错时仍要回到 Promise.all/race/allSettled。