在 async 函数中应使用 await 等待 promise,它自动解包返回 resolved 值,reject 则抛错需 try...catch;避免混用 .then() 与 await,不可在非 async 函数中使用 await;并行请求推荐 promise.all() + await。

在 async 函数中,用 await 等待 Promise 是最直接、最推荐的方式,但要注意它只能用在 async 函数内部,且会暂停执行直到 Promise settle(fulfilled 或 rejected)。
✅ 正确写法:用 await 获取 resolved 值
await 会自动解包 Promise,返回 resolve 的值(不是 Promise 本身)。如果 Promise 被 reject,会抛出错误,需用 try...catch 捕获:
- ✅ 正确:
const data = await fetch('/api').then(res => res.json());(等价于更简洁的const data = await (await fetch('/api')).json();) - ✅ 正确(带错误处理):
try {<br> const res = await fetch('/api');<br> if (!res.ok) throw new Error(`HTTP ${res.status}`);<br> const data = await res.json();<br> console.log(data);<br>} catch (err) {<br> console.error('请求失败:', err);<br>}
❌ 常见错误:混用 .then() 和 await 或忽略返回类型
避免在 await 后再链式调用 .then() —— 这会让逻辑变绕,也容易误以为 await 返回的是 Promise:
- ❌ 错误(多余且易错):
const data = await fetch('/api').then(r => r.json());→ 实际上.then()返回新 Promise,await等的是它,虽能运行但可读性差;应写成两步或直接await (await fetch()).json() - ❌ 错误(忘记
await):const promise = fetch('/api'); const data = promise.json();→data是另一个 Promise,不是 JSON 数据 - ❌ 错误(在非 async 函数里用 await):
function foo() { const x = await someAsync(); }→ 语法错误,必须声明为async function foo()
? 处理多个 Promise:用 Promise.all() + await
需要并行等待多个异步操作时,把 Promise 数组传给 Promise.all(),再用 await 等待整体结果:
- ✅ 推荐:
const [user, posts, comments] = await Promise.all([<br> fetch('/user').then(r => r.json()),<br> fetch('/posts').then(r => r.json()),<br> fetch('/comments').then(r => r.json())<br>]); - ⚠️ 注意:
Promise.all()遇到任意一个 reject 就立即 reject,如需“全都要”结果,改用Promise.allSettled()
? 调试小技巧:确认你 await 的确实是 Promise
有时你以为在等 Promise,其实得到的是普通值(比如函数没返回 Promise、或已缓存结果):
- 用
console.log(x.constructor.name)检查变量是否为Promise - 不确定时加一层保险:
const result = await Promise.resolve(maybePromise); - 箭头函数返回对象字面量要加括号,否则隐式返回
undefined:async () => ({ ok: true })✅;async () => { ok: true }❌(实际返回undefined)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











