async/await 是对 Promises 的语法糖,它让你能写出读起来像同步代码的异步代码。async 函数总是返回一个 Promise;await 暂停函数直到 Promise 落地,然后用其值继续执行。
js
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`); // pause until the response
const user = res.();
user;
} (err) {
.(err);
}
}
顺序执行 vs 并行执行——常见的性能误区
await 一个接一个地执行任务。如果两个请求不相互依赖,按顺序等待它们会慢得不必要:
js
// ❌ sequential — total time = a + b
const a = await getA();
const b = await getB();
// ✅ parallel — total time = max(a, b)
const [a, b] = await Promise.all([getA(), getB()]);
错误处理
使用 try/catch 代替 .catch。被拒绝的 await 承诺会抛出,所以一个 catch 覆盖整个代码块。
底层原理
仍然是 Promises 和微任务队列——await 不会阻塞线程;它交出控制权使其他代码运行,然后继续。别忘记:调用 async 函数而不 await(或 .catch) 它可能会隐藏错误。
为什么这很重要
它使异步流程可读,是为异步工作排序的现代标准——但你必须有意识地用 Promise.all 并行化独立操作。
