Skip to content

Promise 未 await

快速摘要

你调用了一个 `async` 函数却忘了 `await`,于是拿到的是一个 Promise 对象,而不是真正的结果,后续逻辑全部错乱。

为什么发生

  • 调用 async 函数时漏写 await

  • 在非 async 函数里调用 async 函数却没用 .then() 处理

  • forEach 回调里用 awaitforEach 不会等待)

最小示例

✗ 错误代码
async function fetchUser() {
  return { name: "Alice" };
}
const user = fetchUser();
console.log(user.name);
✓ 修复代码
async function fetchUser() {
  return { name: "Alice" };
}
const user = await fetchUser();
console.log(user.name);

没加 awaituser 是 Promise,没有 name 属性。加 awaituser 才是真正的对象。

如何诊断

  • 检查结果是否是 [object Promise] 或打印出来是 Promise 对象

  • 确认调用 async 函数的位置是否用了 await

  • forEach 中改用 for...of 循环来支持 await

如何修复

  • 在调用前加 await,并把外层函数标记为 async

  • .then() 链处理 Promise 结果

  • forEach 改成 for...ofPromise.all + map

如何预防

  • 启用 ESLint require-awaitno-async-promise-executor 规则

  • 对异步函数统一用 async/await 风格,避免混用 .then

相关资源

相关课程

相关练习

← 返回语言