React Promise停留在{Pending}Promise状态已完成



我有这个get请求,它总是返回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将使用其引用打印promise对象,因此当您在第一种情况下记录它时,您看到的已完成的promise可能仍处于挂起状态。

在第二种情况下,您返回的是承诺,而不是result.data

由于异步函数总是返回promise,因此在获取数据之前,您应该await该promise

使用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);
});

最新更新