reactjs - React Promise 卡在 {Pending} Promise Status Fulfilled
问题描述
我有这个获取请求总是返回一个 Promise {}
const appData = api.get('/applicant/'+userId).then(results => results.data);
console.log(appData);
但是当我展开 appData 的控制台日志时,我得到以下信息。
__proto__: Promise
[[PromiseStatus]]: "fulfilled"
[[PromiseValue]]: Object
class1: "Hunter"
faction: "Horde"
name: "lkamnsdflkm"
questions: (16) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
server: "Tichondrius"
spec: "BM"
__proto__: Object
我试过像这样格式化请求
const appData = async () =>
{
const data = await api.get('/applicant/'+userId).then(results => results.data);
return data
}
退货与原件相同。添加 .catch 并不能解决我的问题。我用谷歌搜索了很多不同的关键字来找到答案
编辑:
async getApp(req,res)
{
try {
const app = req.params;
console.log(app);
const exists = await App.find({app});
if(exists)
{
const appData = await App.find(app).then(doc => doc);
//console.log(appData);
res.json(appData);
}
}
catch(error)
{
console.log(error);
}
}
该函数的调用
更新:待处理只发生在 React 组件中。在不同类的组件之外,它工作正常。
解决方案
console.log
将使用其引用打印承诺对象,因此当您在第一种情况下记录它时,您看到的已履行承诺可能仍处于待处理状态。
在第二种情况下,您将返回承诺而不是result.data
由于异步函数总是返回一个承诺,所以你应该await
在获取数据之前承诺
使用async/await
它看起来像:
async function getAppdata() {
// Here we wait for the promise to be fullfilled before getting `result.data`
const { data } = await api.get(`/applicant/${userId}`);
return data;
}
try {
const appData = await getAppData();
console.log(appData);
} catch (e) {
console.error(e);
}
使用then/catch
:
api.get(`/applicant/${userId}`)
.then(result => {
const appData = result.data;
console.log(appData);
})
.catch(error => {
console.error(error);
});
推荐阅读
- sharepoint - 文档库中文档的注释部分
- ios - UIViewController 在 viewDidLoad 之前访问子视图
- python - 使用 python Office 365 API 获取 Sharepoint 文件的最后修改日期/时间
- c# - c# 使用 AutoResetEvent 似乎阻止从串行端口读取
- php - Mysql:查询无法正常工作,未选择 12:00 之间的位置
- xamarin - 在 AVD 配置期间出现“与 Google 服务器通信时出现问题”
- python - 如何在 Python 中访问符号链接的链接文本?
- javascript - 如何递归地在嵌套对象中查找值的键
- postgresql - 查询在 Postgresql 函数中不起作用
- arcore - ARCore - 增强图像增加跟踪的稳定性