JavaScript async/await是什么_它如何简化异步代码

async/await是基于Promise的语法糖,await只能在async函数中使用,会等待Promise settle(含reject并抛错),需try/catch捕获;多个await默认串行,应优先用Promise.all并发。

async/await 是语法糖,不是新机制

它底层完全基于 Promise,没有引入任何新异步模型。写 async function foo() { return 42; } 等价于 function foo() { return Promise.resolve(42); }await bar() 就是 bar().then(...) 的更直观写法。

await 只能在 async 函数里用

直接在顶层或普通函数中写 await fetch('/api') 会报 SyntaxError: await is only valid in async function。常见误用场景包括:

  • 在事件回调(如 button.addEventListener('click', () => { await fn(); }))里忘了给箭头函数加 async
  • Node.js 脚本顶层想直接 await,得改用 async () => { ... }() 或启用 --experimental-top-level-await(仅限 Node.js 14.8+)
  • Vue 选项式 API 的 methods 里写了 await,但没把方法声明为 async method() { ... }

await 会等待 Promise settle,不只是 resolve

await 不仅等 fulfilled,也等 rejected —— 遇到 reject 会直接抛出错误,就像同步代码里 throw 一样。这意味着:

  • 不加 try/catch,错误会冒泡中断后续执行
  • await Promise.reject(new Error('oops')) 等价于 throw new Error('oops')
  • 想捕获错误,必须用 try { await apiCall(); } catch (e) { ... },不能靠 .catch()
async function loadUser() {
  try {
    const res = await fetch('/user');
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error('Failed to load user:', err.message);
    return null;
  }
}

多个 await 默认串行,想并发得用 Promise.all

const a = await fn1(); const b = await fn2(); 是严格串行的:fn2 要等 fn1 完全结束才开始。实际中多数请求可以并发,否则白白浪费时间。

  • 并发写法:const [a, b] = await Promise.all([fn1(), fn2()]);
  • 注意 Promise.all 一有 reject 就整体失败;需要容错用 Promise.allSettled
  • 不要滥用 await 在循环里for (const id of ids) { await fetch(`/item/${id}`); } 是最慢的写法
真正容易被忽略的是错误传播路径和并发控制粒度——await 让代码看起来像同步,但网络延迟、reject 行为、资源竞争一点没少,只是藏得更深了。