私は別の引数を持つ関数呼び出しを3回作っています:for eachループfor非同期コード?
this.getContributorProperties('followers_url', 'contributorFollowers');
this.getContributorProperties('gists_url', 'contributorGists');
this.getContributorProperties('repos_url', 'contributorRepositories');
この関数は以下のようになります。
async getContributorProperties(propertyUrl, propertyName) {
const contributors = await this.addLinkToContributor();
for (let i = 0; i < 10; i += 1) {
axios.get(`${contributors[i][propertyUrl]}?per_page=100&${API_KEY}`).then((res) => {
contributors[i][propertyName] = res.data.length;
});
}
return contributors;
}
それは貢献者の配列(オブジェクトタイプ)をループし、APIコールを行いますそれらのそれぞれのために。私は3つのAPIコールをそれぞれ1つずつ作成する必要があるため、最初は3つの呼び出しを行います。私はそうのようなforeachループを作りたかった私のコードまで乾燥させるために :私はそれがうまく動作3つの呼び出しを行うとき
[
['followers_url', 'contributorFollowers'],
['gists_url', 'contributorGists'],
['repos_url', 'contributorRepositories'],
].forEach(this.getContributorProperties);
foreachループはcomponentDidMount()
です。しかし、私がするときは、エラーが発生します:
Uncaught (in promise) TypeError: Cannot read property 'addLinkToContributor' of undefined
どうすればいいですか?
BONUS:これらのキーと値のペアを各オブジェクトに割り当てるにはどうすればよいですか?
ような何か[*コールバックの中で正しい 'this 'にアクセスするには?*](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback )および/または[*どのように"this"キーワードは動作しますか?*](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –
スタックスニペット( '[<] 'ツールバーボタン)は**実行可能コード**。単なるコードブロックの場合、 '{}'ボタン(またはCtrl + Kか、各行に4つのスペースをインデントする)を使用します。 –