【发布时间】:2018-03-06 06:35:06
【问题描述】:
我正在使用不同的参数进行 3 次函数调用:
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 调用,因此一开始就进行了 3 次调用。 为了干燥我的代码,我想像这样创建一个 forEach 循环:
[
['followers_url', 'contributorFollowers'],
['gists_url', 'contributorGists'],
['repos_url', 'contributorRepositories'],
].forEach(this.getContributorProperties);
forEach 循环位于componentDidMount()
当我打 3 个电话时,它工作正常。但是当我做 forEach 时,我得到一个错误:
Uncaught (in promise) TypeError: Cannot read property 'addLinkToContributor' of undefined
如何让它发挥作用?
奖励:我如何将这些键值对分配给每个对象?
【问题讨论】:
-
堆栈片段(
[<>]工具栏按钮)用于可运行代码。对于代码块,使用{}按钮(或 Ctrl+K 或每行缩进四个空格)。
标签: javascript reactjs foreach async-await frontend