await 必须在 async 函数中使用,暂停执行直至 promise settle,返回其值或抛出错误;支持非 promise 值自动包装,可配合 try/catch 错误处理和 promise.all 实现并行。

await 必须配合 async 函数使用,它让 Promise 的处理逻辑看起来像同步代码,避免了 .then() 链式调用的嵌套,实现真正意义上的“扁平化”。
await 的基本用法和前提条件
await 只能在声明为 async 的函数内部使用,它会暂停当前函数的执行,等待右侧的 Promise settle(fulfilled 或 rejected),然后继续往下执行。返回值就是 Promise 成功时的值;如果 Promise 被拒绝,且没被 try/catch 捕获,就会抛出错误,中断后续代码。
- 不能在普通函数或全局作用域中直接写 await
- await 后面不一定是 Promise:如果不是,会被自动包装成 Promise.resolve(value)
- await 等待的是“thenable”对象(有 then 方法的对象),不严格限定为 Promise 实例
对比传统 Promise 链与 await 扁平写法
比如连续请求两个接口,后一个依赖前一个结果:
传统写法(嵌套):
fetch('/api/user').then(res => res.json())
.then(user => fetch(`/api/posts?uid=${user.id}`))
.then(res => res.json())
.then(posts => console.log(posts));
await 扁平写法(线性):
const userRes = await fetch('/api/user');
const user = await userRes.json();
const postsRes = await fetch(`/api/posts?uid=${user.id}`);
const posts = await postsRes.json();
console.log(posts);
}
逻辑更清晰,变量作用域自然,调试也更容易定位在哪一步出错。
错误处理:用 try/catch 替代 .catch()
await 不会隐式捕获异常,必须显式用 try/catch 包裹可能失败的操作:
async function loadData() {try {
const res = await fetch('/api/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('加载失败:', err.message);
return null;
}
}
注意:每个 await 行都可能抛错,把多个 await 放在一个 try 块里,可统一处理;若需区分不同步骤的错误,可分层 try/catch。
并行执行多个异步操作
await 是串行的,但可以用 Promise.all() + await 实现并行扁平化:
async function loadAll() {const [user, posts, profile] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/profile').then(r => r.json())
]);
return { user, posts, profile };
}
这样既保持了代码扁平,又不牺牲性能——三个请求同时发起,总耗时约等于最慢的那个。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











