async/await 是 promise 的语法糖,旨在让异步代码同步化:简化链式调用、统一 try/catch 错误处理、支持 promise.all 并行;需在 async 函数内使用,返回 promise,避免无谓串行。

async 和 await 是 Promise 的语法糖,核心目标是让异步代码写得像同步一样自然,直接解决 Promise 链嵌套深、错误分散、变量传递麻烦等问题。
把多层 .then 串行调用变成 await 序列
原来需要层层传参的 Promise 链:
- fetchUser().then(u => fetchOrder(u.id)).then(o => fetchProduct(o.pid))
现在只需定义 async 函数,逐行 await:
- const user = await fetchUser()
- const order = await fetchOrder(user.id)
- const product = await fetchProduct(order.pid)
每一步结果可直接赋值、复用,无需箭头函数包裹,作用域清晰,逻辑线性。
用 try/catch 统一处理所有异步错误
Promise 链中每个 .then 都可能出错,.catch 容易漏写或位置不对;async/await 中所有 await 抛出的 reject 都会被同一 try/catch 捕获:
- try { const user = await fetchUser(); const order = await fetchOrder(user.id); } catch (err) { console.error('任一请求失败:', err); }
不再需要为每个步骤单独配 .catch,也不用担心深层嵌套里异常被吞掉。
独立请求用 Promise.all + await 并行执行
若多个接口无依赖关系,串行 await 会拖慢整体耗时。改用 Promise.all 同时发起:
- const [user, order, config] = await Promise.all([fetchUser(), fetchOrder(), fetchConfig()]);
解构赋值让结果组织直观;注意 Promise.all 遇错即停,如需容错可用 Promise.allSettled。
注意基本约束和常见误区
async/await 不是万能胶,几个硬性前提必须满足:
- await 只能在 async 函数内部使用,顶层作用域不能直接 await
- async 函数返回值一定是 Promise,调用方仍需 .then 或 await 获取结果
- 避免把本可并行的操作写成串行 await,否则性能反而下降
- 回调函数(如 setTimeout、addEventListener)里不能直接写 await,需包装成 async 函数或用 IIFE











