Async/Await 是 JavaScript 对 Promise 的封装语法糖,不改变异步本质;async 函数总返回 Promise,await 在 async 内部暂停执行以等待 Promise settle,使异步代码更易读、调试和错误处理。
Async/Await 是 JavaScript 对 Promise 的封装语法,不改变异步本质,也不替代 Promise。它让基于 Promise 的异步逻辑写起来像同步代码,但执行时仍是非阻塞的。
一个 async 函数总是返回 Promise;哪怕你 return 42,实际返回的是 Promise.resolve(42)。而 await 只能在 async 函数内部使用,它会“暂停”函数执行(只是语义暂停,线程没卡住),等待右侧的 Promise settle 后继续。
最简结构就是给函数加 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);
}
}
注意几个关键点:
await 右侧必须是 Promise(或 thenable),否则会被自动包装成 Promise.resolve(value)
await(ES2025 起支持顶层 await,但仅限模块环境,且 Node.js 需 .mjs 或 type: "module")await 不会捕获同步错误,比如 await null.foo 会立即抛出 TypeError,需靠 try/catch 捕获对比同样逻辑的 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,第二个等第一个完全结束才开始——这不是你想要的并发?得用 Promise.all([p1, p2]) 包一层再 await
try/catch,或者只包了部分 await,未捕获的 Promise 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 只是把选择权更清晰地交还给你。