async/await

async/await

孤独的哈士奇 0 2026-04-21

async/await的设计思想类很似 Generator + co,但并不是基于 Generator 实现的。
它是 V8 引擎原生支持的特性,性能更好,机制更直接。

可以理解成: await把后续代码注册成Promise的.then回调,放入微任务队列。

await promise 等价于:
await 后面的代码,用 .then 包起来,交给 Promise 处理。

基本语法

async function fetchData() {
  try {
    const response = await fetch('/api/user');
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error('出错了:', error);
  }
}

核心优势

特性

回调函数

Promise

async/await

代码可读性

🔴 差

🔵 中

🟢 优

错误处理

🔴 繁琐

🔵 集中

🟢 统一

阻塞主线程

❌ 否

❌ 否

❌ 否

学习成本

🔵 低

🔵 中

🟢 高(需理解原理)

总结

async/await只是让异步代码更好写、更好读。但它还是解决不了异步本身的复杂性。

  1. “它是 Promise 的语法糖,让异步代码更易读。

  2. 但它本质还是异步,await会把后续逻辑注册为 .then 回调,进入微任务队列。

  3. 使用时要注意并行优化、错误捕获,避免在数组方法中误用。