首页 > 解决方案 > 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 组件中。在不同类的组件之外,它工作正常。

标签: reactjspromiseaxios

解决方案


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

推荐阅读