async/await 是什么

async/await 是 Promise 的语法糖,让异步代码看起来像同步,可读性大幅提升。

基本写法

async function getData() {
  const resp = await fetch('/api/data');
  const json = await resp.json();
  return json;
}

错误处理

async function load() {
  try {
    const data = await fetchData();
    render(data);
  } catch (err) {
    console.error('加载失败', err);
    showError();
  }
}

并发优化

await 会阻塞,串行会慢。互相独立的请求用 Promise.all 并发:

// 慢:逐个等待
const a = await fetchA();
const b = await fetchB();

// 快:并发
const [a, b] = await Promise.all([fetchA(), fetchB()]);

并行但有先后

const all = await Promise.allSettled([p1(), p2(), p3()]);
// 各自结果,不会因单个失败而整体中断

for-await 处理流

for await (const chunk of asyncIterable) {
  process(chunk);
}
要点:async 函数永远返回 Promise;await 只能在 async 函数内使用;用 Promise.all 提升并发度。