2017-05-30 24 views
0

我正在學習一個教程,其中要求來自git API的數據,並且評分算法會對這些數據進行排序。axios promise在「axios.all」函數中返回正確的值,但在「then」函數中未定義。

戰鬥函數將採用兩個元素的陣列,即兩個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功能ORK簡介(用戶名,追隨者,等)和它們的回購(回購名的成績。EAH用戶等)。所以我已經省略了這兩個函數的代碼,因爲我已經知道它們確實有效。此外,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) 
     } 
    }) 
} 

問題:

在「戰鬥」回調函數應該接收大小爲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功能

糾正我,如果我錯了,它的輸入,但在承諾,是不來自「axios.all」方法的輸出應該是「then」方法的輸入。那麼,如果console.log語句顯示axios.all正在輸出正確的數據,爲什麼我會得到undefined?

回答

2

您的getUserData函數不返回任何內容。如下更改:

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

這種行爲是因爲你當你做response.map,你替換所有undefinedconsole.log回報undefined)的項目將返回undefined值的數組。

相反,從異步調用返回實際的結果:

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

感謝幫忙。我試過你的解決方案,但它仍然給出了兩個未定義的元素數組 –

+0

@AndrewBrick請用你正在使用的確切代碼更新你的問題。 – str

+0

這個問題肯定存在於map函數中,我確定getUserData返回的是實際數據,但在它傳入「then」方法之前,它需要通過map,但映射不知何故使它不確定 –