Promise 不 Awaited
快速摘要
你 called 异步函数不使用 `等待`, 所以你 获取 Promise 对象相反的 实际 result 你 expected.
为什么发生
Forgot
等待keyword 之前异步函数 callCalled 异步函数 in 非-异步上下文不使用
.然后()Assigned result 的异步 call 到变量 and used 它 as 值
最小示例
✗ 错误代码
async function getData() {
return fetch("/api").then(r => r.json());
}
const data = getData();
console.log(data); // [object Promise]✓ 修复代码
async function getData() {
return fetch("/api").then(r => r.json());
}
const data = await getData();
console.log(data); // actual resultgetData() 返回 Promise — 不使用 等待, 数据 是 Promise 对象, 不 resolved 值.
如何诊断
Log result — 如果它 shows
[对象 Promise], 你 missed等待检查函数 signature — 做它 返回 Promise?
验证 calling 函数是
异步如果你're using等待
如何修复
添加
等待之前异步函数 call制作 calling 函数
异步如果它 isn't alreadyUse
.然后()相反的等待如果你 能't 制作函数异步
如何预防
Use
异步/等待consistently and 启用 ESLintrequire-await规则检查返回类型 — 如果函数返回 Promise, 你需要
等待
相关资源
相关课程
- 异步 JavaScript
学习关于异步/等待 and Promise
相关练习
- Predict 函数 Call Result
练习 predicting 函数 call results.