async/await 是 JavaScript 中基于 Promise 的异步语法糖,使异步代码更直观易读;async 函数自动返回 Promise,await 在 async 内部暂停执行以等待 Promise 结果,支持 try/catch 统一错误处理。

async/await 是 JavaScript 中处理异步操作的语法糖,它让异步代码写起来像同步代码一样直观,大幅降低回调嵌套和 Promise 链的复杂度。
async 函数:自动返回 Promise 的函数
在函数声明前加 async 关键字,该函数就变成异步函数。它会自动把返回值包装成 Promise;即使你 return 一个普通值,也会被转为 Promise.resolve(value)。
- 如果 return 一个 Promise,就直接返回那个 Promise
- 如果 throw 错误,等价于返回
Promise.reject(error) - 不能用在普通函数、箭头函数(除非显式声明 async)或全局作用域中
await:暂停执行,等待 Promise 完成
await 只能在 async 函数内部使用,它会让 JS 引擎暂停当前 async 函数的执行,直到右侧的 Promise settle(fulfilled 或 rejected),再继续往下走。
- 如果 Promise 成功,
await promise的结果就是 resolve 的值 - 如果 Promise 失败,会抛出错误,可用 try/catch 捕获
- await 后面不一定是 Promise——任何值都会被自动转为 resolved 的 Promise
对比传统 Promise 写法,更清晰易读
比如发三个顺序请求:
立即学习“Java免费学习笔记(深入)”;
用 Promise 链写:
fetch('/api/user')
.then(res => res.json())
.then(user => fetch(`/api/posts?userId=${user.id}`))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
用 async/await 写:
async function loadPosts() {
try {
const userRes = await fetch('/api/user');
const user = await userRes.json();
const postsRes = await fetch(`/api/posts?userId=${user.id}`);
const posts = await postsRes.json();
console.log(posts);
} catch (err) {
console.error(err);
}
}
逻辑线性、错误统一处理、变量作用域自然,调试也更接近同步代码体验。
常见注意事项和技巧
- await 不会阻塞整个线程,只是暂停当前 async 函数,其他任务照常运行(仍是事件循环机制)
- 多个请求无依赖时,别傻等——用
Promise.all([await p1, await p2])改成并发请求 - 顶层 await 现已在模块(.mjs 或 type="module" 的 script)中支持,但暂不能用于普通脚本
- 不要滥用 async/await:简单同步逻辑或已知立即完成的操作,没必要包一层 async
基本上就这些。async/await 不是黑魔法,背后仍是 Promise 和微任务队列,但它确实让异步流程更符合人类直觉,写起来不费劲,读起来不烧脑。










