我正在尝试使用async / await来调用API并在迭代多级对象/数组并提取相关数据之前等待结果。我遇到的问题是我无法访问forLoop之外的数据。见下文:
const gameStrings = ['LAA-NYM', 'LAA-TB', 'NYY-HOU'];
const startingPlayers = [];
gameStrings.forEach(async function(element, i) {
let query = await fetch('fakeapi.com', element);
query.gamestartinglineup.teamLineup.forEach(b => b.actual.starter.forEach(c => {
if (c.player) {
const player = {
id: c.player.FirstName + '-' + c.player.LastName + '-' + c.player.ID
}
startingPlayers.push(player);
}
}));
startingPlayers ['Mookie-Betts-10456','...','...']< - 在forEach中,数据就在这里!
})
startingPlayers []< - 在forEach之外,它是一个空数组......
答案 0 :(得分:1)
for(let i of items){...
时,请使用.forEach(t => {...
代替async
循环
const gameStrings = ['LAA-NYM', 'LAA-TB', 'NYY-HOU'];
const startingPlayers = [];
for (let element of gameStrings) {
let query = await fetch('fakeapi.com', element);
query.gamestartinglineup.teamLineup.forEach(b => b.actual.starter.forEach(c => {
if (c.player) {
const player = {
id: c.player.FirstName + '-' + c.player.LastName + '-' + c.player.ID
}
startingPlayers.push(player);
}
}));
}