Async/await 是 JavaScript 中基于 Promise 的异步语法糖,使异步代码更直观;async 函数自动返回 Promise,await 暂停函数执行以等待 Promise 结果,支持 try/catch 统一错误处理,并可通过 Promise.all 实现并行请求。

Async/await 是 JavaScript 中处理异步操作的语法糖,它让基于 Promise 的异步代码写起来像同步代码一样直观,大幅降低回调嵌套和 Promise 链式调用带来的复杂度。
Async/await 的基本用法
async 关键字用于声明一个函数是异步的,它会自动把返回值包装成 Promise;await 关键字只能在 async 函数内部使用,用于“等待”一个 Promise 被兑现(fulfilled 或 rejected),并获取其结果。
- async 函数总是返回 Promise,即使你 return 一个普通值,也会被自动 resolve
- await 后面可以跟 Promise、任意值(非 Promise 会被立即 resolve)或另一个 async 函数调用
- await 会让 JS 引擎暂停当前 async 函数的执行(不阻塞主线程),等 Promise settled 后再继续
对比传统 Promise 写法
比如发起一个 API 请求:
用 Promise 链写:
fetch('/api/user').then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
用 async/await 写:
try {
const res = await fetch('/api/user');
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
结构更线性,错误处理统一用 try/catch,逻辑更贴近自然阅读顺序。
多个异步操作的执行控制
await 默认是串行等待:前一个完成才开始下一个。但你可以用 Promise.all() 配合 await 实现并行请求:
- 串行(依次等待):
await api1(); await api2(); - 并行(同时发起,等待全部完成):
await Promise.all([api1(), api2()]); - 有依赖关系时,仍需按需 await,避免过早并行导致数据未就绪
常见误区与注意事项
await 不是万能的“暂停整个程序”,它只暂停所在 async 函数的执行;外部代码(如事件循环中的其他任务)照常运行。
- 不能在顶层作用域(非 async 函数内)直接使用 await(ES2022 起支持顶层 await,但仅限模块环境)
- 忘记加 async 就用 await 会报语法错误;反过来,async 函数里不用 await 也没问题,只是失去意义
- 错误必须捕获:未 catch 的 rejected Promise 会变成 unhandled rejection,可能触发全局错误事件










