javascript - 将元素推入数组仅在循环内有效
问题描述
我得到了一些我从 API 调用的数据,为此我正在使用 axios。当检索到数据时,我将其转储到一个名为“RefractorData()”的函数中,只是为了对其进行一点组织,然后将其推送到现有数组中。问题是,我的数组被填充在 forEach 中,我可以在那里 console.log 我的数据,但是一旦我退出循环,我的数组就是空的。
let matches: any = new Array();
const player = new Player();
data.forEach(
async (match: any) => {
try {
const result = await API.httpRequest(
`https://APILink.com/matches/${match.id}`,
false
);
if (!result) console.log("No match info");
const refractored = player.RefractorMatch(result.data);
matches.push({ match: refractored });
console.log(matches);
} catch (err) {
throw err;
}
}
);
console.log(matches);
现在 forEach 中的第一个 console.log 正确显示数据,forEach 之后的第二个显示空数组。
解决方案
设法用Promise.all()和Array.prototype.map() 做到这一点。
const player = new Player();
const matches = result.data;
const promises = matches.map(async (match: any) => {
const response: any = await API.httpRequest(
`https://API/matches/${match.id}`,
false
);
let data = response.data;
return {
data: player.RefractorMatch(data)
};
});
const response: any = await Promise.all(promises);
推荐阅读
- python - How to bypass self signed certificate verify in python pika to rabbitmq?
- flutter - Running Firestore transaction at same location is crashing the app
- perl - Perl获取特定日期前十天的日期
- sql - 根据条件连接多个表
- python - 在字符串中查找文本并打印多个结果
- python - 为什么 pandas Styler 'to_excel' 方法不保存百分比格式?
- r - 如何通过对节点进行分组来降低邻接矩阵的分辨率
- debugging - 使用 clion 调试 rust 时,如何修复奇怪的非 ascii 字符动态链接器错误?
- sql - 尝试更新 where 子句以仅适用于某个值
- javascript - 固定范围并填充 Apache eCharts 中的缺失值