async/await 本质是封装 Promise 链,使异步流程线性可读;它不阻塞线程,需在 async 函数中使用 await;应合理搭配 Promise.all() 实现并发,避免无谓串行,并主动处理错误。

用 async/await 写异步代码,就像写同步代码一样自然——它不会真正“消除”回调,而是把底层的 Promise 链和 .then() 调用封装起来,让你专注逻辑本身。
理解 async/await 的本质
async 函数返回一个 Promise,await 只能在 async 函数内部使用,它会暂停函数执行(不阻塞线程),等待右侧的 Promise settle(fulfilled 或 rejected)后,再继续向下运行。
关键不是“变同步”,而是“让异步流程看起来像同步”——这大幅降低了心智负担。
从回调地狱到 await 的直观对比
比如连续请求用户、订单、商品信息:
传统回调写法(嵌套加深、错误处理分散):
AI 舌诊面诊问诊医疗系统 + 诊疗商城系统源码是一套结合 AI 辅助诊断与商品转化的健康类程序,基于浩创云、ThinkPHP(PHP)开发,支持微信服务号与 H5 端,适合做中医舌诊面诊问答、健康建议推送以及配套诊疗商品的运营。
getUser(id, (err, user) => {
if (err) return handleError(err);
getOrders(user.id, (err, orders) => {
if (err) return handleError(err);
getProduct(orders[0].pid, (err, product) => {
if (err) return handleError(err);
console.log(product.name);
});
});
});
用 async/await 改写(线性、可读、错误集中):
async function showFirstProduct(userId) {
try {
const user = await getUser(userId);
const orders = await getOrders(user.id);
const product = await getProduct(orders[0].pid);
console.log(product.name);
} catch (err) {
handleError(err);
}
}
处理并发请求:别滥用 await 串行化
如果多个请求彼此独立,用 await 一个接一个写,反而变慢。此时应配合 Promise.all():
- ✅ 正确:并行发起,等全部完成
- ❌ 错误:用 await 逐个等,变成串行
示例:
// 并行获取用户和公告(无依赖) const [user, notice] = await Promise.all([ fetchUser(), fetchNotice() ]); // 而不是: // const user = await fetchUser(); // const notice = await fetchNotice(); // 多等一倍时间
错误处理要主动,别只靠 try/catch
await 后的 Promise 若 rejected,会直接抛出异常,被最近的 try/catch 捕获。但要注意:
- 未被
try/catch包裹的await会把错误冒泡到函数返回的 Promise 中 - 对可能失败的操作,推荐显式处理,比如
await api().catch(() => null) - 避免在循环中
await大量独立请求 —— 考虑分批 +Promise.allSettled()
async/await 不是银弹,但它把异步控制流从“推演回调路径”变成了“阅读执行顺序”,这是提升可维护性的关键一步。

















