【问题标题】:Unexpected Promise <state> pending being returned using axios [duplicate]使用 axios 返回意外的 Promise <state> 未决 [重复]
【发布时间】:2020-12-02 08:27:40
【问题描述】:

我希望有人能在这里指出我的方法的错误。

我目前有两个功能。一个是 getData,它是一个异步函数,可以简单地通过 API 调用请求数据。第二个函数是 getRandomCategories,它封装了 getData 函数调用并将异步操作的值保存在一个名为 res 的变量中。 getRandomCategories 中的其余代码将响应数据处理为一个数字数组,其中每个数字代表一个类别。

当我在 getRandomCategories 函数中使用调试器语句时(就在 try 块中的 return 语句之前),我从名为 apiCallCategoryArray 的变量中获取了我期望的数据类型 - 它是一个数字数组,每个数字代表一个类别。生活是美好的。

这就是问题所在。当我调用 getRandomCategories 期望 dataArray 变量(在代码 sn-p 的底部)保存一个数字数组时 - 我得到了一个状态为待处理的 Promise??

我不明白为什么 apiCallCategoryArray 变量的值使用调试器显示为我的预期值(因此我在函数中返回它)但是当我无法访问该值时调用函数。为什么我会收到一个处于未决状态的 Promise?我错过了什么?

下面是我的代码:

async function getData(endpoint, query, value) {
  return await axios.get(
    `http://jservice.io/api/${endpoint}?&${query}=${value}`
  )
}

// createa a function that will return 6 random categories
async function getRandomCategories() {
  try {
    const res = await getData('categories', 'count', 50)
    const data = res.data;
    const categories = filterCategoryData(data); // I'm filtering for category id with clues_count === 5
    const categoryIdArr = mapCategoryIds(categories); // an array of just category Ids
    const shuffledCategoryIds = shuffle(categoryIdArr);
    const apiCallCategoryArray = takeFirstXItems(shuffledCategoryIds, 6);
    debugger//  the value is what I'm expecting an array of numbers with length = 6
    return apiCallCategoryArray
  } catch (err) {
    console.log(err);
  }
}



//Solution one: Does not work. I'm getting a promise back instead of an array of numbers
const dataArray = getRandomCategories()
console.log(dataArray) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers

// Solution two: Does not work either. I'm still getttng a promise back instead of an array of numbers
const dataArray2 = getRandomCategories().then((array) => {
  return array
})
console.log(dataArray2) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers

我的目标是让我的 dataArray 变量保存通过调用 getRandomCategories() 返回的数字数组(不是带有待处理的 Promise)。所以我可以将此值用于我的代码中的其他函数。

提前感谢您的时间和回复。

【问题讨论】:

    标签: async-await axios es6-promise


    【解决方案1】:

    你需要使用 async, await 来取回你的 Promise 数据。像这样

    async function test(){
      let dataArray2 = await getRandomCategories();
      console.log(dataArray2);
    };
    

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 1970-01-01
      • 2016-12-27
      • 2021-09-19
      • 1970-01-01
      • 2019-05-08
      • 2020-06-05
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多