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