【问题标题】:axios promise returns correct value in "axios.all" function, but is undefined in the "then" functionaxios promise 在“axios.all”函数中返回正确的值,但在“then”函数中未定义
【发布时间】:2017-10-31 02:28:12
【问题描述】:

我正在关注一个教程,其中请求来自 git API 的数据,并且评分算法将对这些数据进行排序。

battle 函数将采用一个包含两个元素的数组,即两个 github 用户。我们从 getUserData 方法中检索每个用户的个人资料和分数

module.exports = {
  battle: function(players) {
      return axios.all(players.map(getUserData))
        .then(response => {
           response.forEach( each=>console.log(each));
           return response;
       })
  }
}

getProfile 和 getRepos 函数在检索具有用户个人资料(用户名、关注者等)及其存储库(存储库名称等)数据的对象时正确运行。所以我已经省略了这两个函数的代码,因为我已经知道它们确实有效。此外,calculateScore 方法也可以正常工作并按预期返回输出。

console.log 语句显示带有键“profile”和“score”的对象已正确制作,并按预期打印出配置文件对象数据和分数。到目前为止一切顺利。

function getUserData(player) {
  axios.all([
    getProfile(player),
    getRepos(player)
  ])
    .then(function(data) {
        var profile = data[0];
        var repos = data[1];

        console.log({
            profile: profile,
            score: calculateScore(profile, repos)
        })

        return {
            profile: profile,
            score: calculateScore(profile, repos)
        }
    })
}

问题:

“battle”中的回调函数应该接收一个大小为 2 的数组,其中每个元素都包含该特定玩家的个人资料和得分。例如:

[
 {
   profile: {profile data for player1...}
   score: 10 //or whatever the score is
 },
 {
   profile: {profile data for player2...}
   score: 2 //or whatever the score is
 }
]

但回调函数从 axios.all 函数接收 [undefined, undefined] 作为其输入

如果我错了,请纠正我,但在承诺中,“axios.all”方法的输出不应该是“then”方法的输入。那么,如果 console.log 语句显示 axios.all 正在输出正确的数据,为什么我会得到未定义?

【问题讨论】:

    标签: javascript promise axios


    【解决方案1】:

    您的getUserData 函数不返回任何内容。修改如下:

    function getUserData(player) {
      return axios.all([
      // ...
      ]);
    }
    

    这种行为是因为您在执行response.map 时返回了一个undefined 值数组,其中所有项目都替换为undefinedconsole.log 返回undefined)。

    相反,从异步调用返回实际结果:

    module.exports = {
      battle: function(players) {
          return axios.all(players.map(getUserData))
            .then(response => {
                response.forEach(each => console.log(each));
                return response;
            });
      }
    }
    

    【讨论】:

    • 感谢您的帮助。我尝试了您的解决方案,但它仍然给出了一个包含两个未定义元素的数组
    • @AndrewBrick 请使用您现在使用的确切代码更新您的问题。
    • 问题肯定出在map函数上,我确定getUserData返回的是实际数据,但是在传入“then”方法之前,需要经过map,但是map不知怎么做到了未定义
    猜你喜欢
    • 2020-10-03
    • 2020-02-26
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多