Async/Await 是 JavaScript 对 Promise 的封装语法糖,不改变异步本质;async 函数总返回 Promise,await 在 async 内部暂停执行以等待 Promise settle,使异步代码更易读、调试和错误处理。

Async/Await 是什么:语法糖,不是新机制
Async/Await 是 JavaScript 对 Promise 的封装语法,不改变异步本质,也不替代 Promise。它让基于 Promise 的异步逻辑写起来像同步代码,但执行时仍是非阻塞的。
一个 async 函数总是返回 Promise;哪怕你 return 42,实际返回的是 Promise.resolve(42)。而 await 只能在 async 函数内部使用,它会“暂停”函数执行(只是语义暂停,线程没卡住),等待右侧的 Promise settle 后继续。
怎么写:async 函数 + await 表达式
最简结构就是给函数加 async 前缀,内部用 await 等待 Promise:
async function fetchUser() {
try {
const res = await fetch('/api/user');
const user = await res.json();
return user;
} catch (err) {
console.error('请求失败', err);
}
}
注意几个关键点:
立即学习“Java免费学习笔记(深入)”;
-
await右侧必须是Promise(或 thenable),否则会被自动包装成Promise.resolve(value) - 不能在顶层作用域直接写
await(ES2022 起支持顶层await,但仅限模块环境,且 Node.js 需.mjs或type: "module") -
await不会捕获同步错误,比如await null.foo会立即抛出TypeError,需靠try/catch捕获
为什么用它:比 .then() 链更易读、更可控
对比同样逻辑的 Promise 链写法:
// Promise 链(嵌套感强,错误处理分散)
fetch('/api/user')
.then(res => res.json())
.then(user => {
console.log(user);
return fetch(`/api/posts?uid=${user.id}`);
})
.then(res => res.json())
.catch(err => console.error(err));
用 async/await 就平铺直叙:
async function loadUserData() {
try {
const res = await fetch('/api/user');
const user = await res.json();
console.log(user);
const postsRes = await fetch(`/api/posts?uid=${user.id}`);
const posts = await postsRes.json();
return { user, posts };
} catch (err) {
console.error('加载失败', err);
}
}
优势明显:
- 错误统一用
try/catch处理,不用每个.then()后都接.catch() - 调试友好:断点可逐行停在
await行,不像.then()回调里跳来跳去 - 条件分支自然:比如
if (user.isAdmin) await fetch('/api/admin'),不用拆成多个.then()块
容易踩的坑:await 不等于同步,也不等于自动并发控制
常见误解和陷阱:
-
await是串行的:连续写两个await,第二个等第一个完全结束才开始——这不是你想要的并发?得用Promise.all([p1, p2])包一层再await - 忘记处理拒绝:没写
try/catch,或者只包了部分await,未捕获的Promiserejection 会变成 unhandled rejection - 误以为
async让函数变“快”:它不加速 I/O,只是改善代码组织;CPU 密集型任务仍需Web Worker或分片 - 在循环中滥用
await:比如for (const id of ids) await fetch(`/item/${id}`)是逐个请求,想并行就得改用Promise.all(ids.map(id => fetch(...)))
真正难的从来不是语法,而是判断哪些操作该串行、哪些该并发、哪些该降级兜底——async/await 只是把选择权更清晰地交还给你。











