【发布时间】: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