async/await 是 JavaScript 处理异步的语法糖,async 函数自动返回 Promise,await 暂停函数执行等待 Promise 完成且不阻塞主线程,需在 async 函数内使用并配合 try/catch 错误处理,并发请求应优先用 Promise.all。

async/await 是 JavaScript 中处理异步操作的语法糖,它让异步代码看起来像同步代码,更易读、易维护。核心在于:用 async 声明函数,用 await 暂停执行、等待 Promise 完成,期间不阻塞主线程。
async 函数:自动返回 Promise
在函数声明前加 async,该函数就变成异步函数,无论内部是否含 await,它都会自动包装返回值为 Promise:
- 返回普通值(如
return 42)→ 等价于Promise.resolve(42) - 抛出错误(
throw new Error())→ 等价于Promise.reject(...) - 不写 return → 返回
Promise.resolve(undefined)
await:只能在 async 函数内使用
await 后面必须跟一个 Promise(或任何值,会被自动转为 resolved Promise),它会“暂停”当前 async 函数的执行,等 Promise settle(fulfilled 或 rejected)后再继续。注意:await 不阻塞整个线程,只是暂停当前函数逻辑,其他任务仍可运行。
- ✅ 正确:
const data = await fetch('/api/user').then(r => r.json()) - ❌ 错误:在普通函数或顶层作用域直接写
await doSomething()(会报 SyntaxError) - ⚠️ 注意:await 后的 Promise 被 reject,会抛出错误,需要用 try/catch 捕获
错误处理:用 try/catch 替代 .catch()
相比链式调用中的 .catch(),await 更自然地配合 try/catch 使用:
立即学习“Java免费学习笔记(深入)”;
async function getUser() {
try {
const res = await fetch('/api/user');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
return user;
} catch (err) {
console.error('获取用户失败:', err.message);
throw err; // 可选择重新抛出供上层处理
}
}
并发请求:避免无意义的串行等待
如果多个异步操作彼此独立,不要连续 await,否则变成串行(耗时相加)。应先发起所有 Promise,再 await 它们:
- ❌ 串行(慢):
const a = await api1(); const b = await api2(); - ✅ 并发(快):
const [a, b] = await Promise.all([api1(), api2()]); - ? 补充:需要容错时可用
Promise.allSettled(),它不会因某个失败而中断











