async/await的核心目标是让异步代码具备同步的阅读体验和控制流逻辑,仍运行于事件循环中且不阻塞主线程;async声明函数返回promise,await在async函数内等待promise settled并解包值,本质是暂停执行上下文而非线程。

async/await 的核心目标不是“伪装同步”,而是让异步代码拥有同步的阅读体验和控制流逻辑——它依然运行在事件循环中,不阻塞主线程,但写法更贴近直觉。
用 async 声明函数,用 await 暂停执行点
async 是函数声明的修饰符,表示该函数返回一个 Promise;await 只能在 async 函数内部使用,用于等待 Promise 状态 settled(fulfilled 或 rejected),并解包其值。它不会真正“暂停”线程,而是暂停当前 async 函数的执行上下文,把控制权交还给事件循环。
例如:
async function fetchUserData() {
try {
const res = await fetch('/api/user'); // 等待网络请求完成
const user = await res.json(); // 等待 JSON 解析完成
console.log(user.name); // 后续逻辑自然衔接
} catch (err) {
console.error('加载失败:', err);
}
}
避免常见陷阱:不要滥用 await 或遗漏错误处理
await 是逐行顺序执行的,如果多个请求彼此独立,用 await 串行写会变慢;同时,未包裹在 try/catch 中的 await 一旦抛错,会直接让整个 async 函数 reject,可能引发未捕获异常。
- ✅ 独立请求尽量并发:用 Promise.all([await p1, await p2]) 改成 Promise.all([p1, p2]),再 await 解构
- ✅ 错误必须捕获:每个 await 前后都应考虑失败路径,推荐统一用 try/catch 包裹逻辑块
- ❌ 不要在循环中无条件 await(如 for 循环里 await apiCall(i))——除非你明确需要串行
与 Promise 链对比:更清晰的错误传播和变量作用域
相比 .then().catch() 链,async/await 让错误能像同步代码一样冒泡,try/catch 范围明确;中间变量也不用层层传递,作用域天然连贯。
比如连续调用三个接口,且后一个依赖前一个结果:
// Promise 链写法(嵌套、变量分散)
fetch('/order')
.then(res => res.json())
.then(order => fetch(`/user/${order.userId}`))
.then(res => res.json())
.then(user => fetch(`/profile/${user.id}`))
.then(res => res.json())
.then(profile => console.log(profile))
.catch(err => console.error(err));
// async/await 写法(平铺、变量直观)
async function loadOrderProfile() {
try {
const order = await (await fetch('/order')).json();
const user = await (await fetch(`/user/${order.userId}`)).json();
const profile = await (await fetch(`/profile/${user.id}`)).json();
console.log(profile);
} catch (err) {
console.error(err);
}
}
理解 await 的本质:它等的是 Promise,不是“函数”
await 后面不一定要是 Promise,但会自动用 Promise.resolve() 包装非 Promise 值;如果后面是普通值(如 42、'hello'),await 会立即返回它——这说明 await 关注的是“可等待对象”的状态,而非语法形式。
- await 42 → 立即得 42
- await Promise.resolve(100) → 等微任务后得 100
- await someAsyncFn() → 等它返回的 Promise 完成
- await null / undefined → 等效于 Promise.resolve(null)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











