2017-05-30 5 views
0

git APIからのデータが要求され、得点アルゴリズムがそのデータを注文するチュートリアルに従っています。axios.all関数で正しい値を返しますが、 "then"関数では未定義です

バトル関数は、2つの要素、つまり2つの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関数からその入力として[未定義、未定義]受信している

は私が間違っているなら、私を修正したが、約束では、ではありません"then"メソッドの入力であると想定される "axios.all"メソッドからの出力。なぜ、console.log文がaxios.allが正しいデータを出力していることを示しているのですか?

答えて

2

getUserData関数は何も返しません。以下のように変更します

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

あなたはundefinedconsole.log戻りundefined)を持つすべての項目を置き換えるresponse.mapを行うときにundefined値の配列を返すための行動であること。

は代わりに、非同期呼び出しから実際の結果を返します:

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

感謝を助けるため。私はあなたのソリューションを試しましたが、未定義の2つの要素が配列されています –

+0

@AndrewBrick今すぐ使用しているコードで質問を更新してください。 – str

+0

問題は間違いなくマップ関数にありますが、getUserDataは実際のデータを返しますが、 "then"メソッドに渡される前にマップを通過する必要がありますが、マップはどういうわけか未定義にします –

関連する問題