async/await 通过线性书写异步代码解决回调地狱问题:函数加 async 返回 promise,调用前加 await 暂停执行;支持 try/catch 统一错误处理,并可结合 promise.all() 并发请求提升性能。

用 async 和 await 替代嵌套的 .then() 链,能让异步代码像同步一样线性书写,直接解决回调地狱问题。
把 Promise 链改造成 async/await
传统 Promise 回调地狱常表现为多层 .then() 嵌套,可读性差、错误处理麻烦。改成 async/await 后,异步调用变成“等待—执行”的自然流程。
- 将函数声明加上
async关键字,它会自动返回 Promise - 在调用 Promise 方法前加
await,暂停执行直到 Promise 完成 - 多个异步操作依次写,不用嵌套,也不用传参层层接力
顺序执行多个异步操作
比如依次获取用户、订单、商品信息,原来可能这样写:
getUser().then(user =>
getOrders(user.id).then(orders =>
getItems(orders[0].id).then(items => console.log(items))
)
)
用 async/await 就变成:
async function loadUserData() {
const user = await getUser();
const orders = await getOrders(user.id);
const items = await getItems(orders[0].id);
console.log(items);
}
逻辑清晰,变量作用域自然,调试也更直观。
统一错误处理:用 try/catch 代替 .catch()
Promise 链中每个 .then() 后都要配 .catch() 才能捕获中间任一环节的错误;而 async/await 可用标准 try/catch 包裹整个流程。
- 所有
await行的异常都会被同一个catch捕获 - 无需重复写错误处理逻辑,也避免漏掉某一层的
.catch() - 可以针对不同错误做差异化处理(例如重试、降级、提示)
并发请求不阻塞:用 Promise.all() 配合 await
如果几个请求彼此独立,不需要等前一个完成再发下一个,就别用 await 串行,改用 Promise.all() 并发发起:
async function loadAll() {
const [user, posts, profile] = await Promise.all([
getUser(),
getPosts(),
getProfile()
]);
return { user, posts, profile };
}
既保持代码简洁,又提升性能——这才是 async/await 的正确打开方式。











