在几个fetch请求中的for循环中使用fetch



好吧,伙计们,我真的被困在这里该做什么来确保一切按顺序执行。感觉我错过了一个等待或其他非常简单的事情,但我似乎真的无法理解为什么我的返回等待不只是在所有其他提取完成后返回。

async function generateData(region, user) {
const apiKey = "APIKEY";
let promises = [];
let gameData = [];
fetch("https://" + region + ".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + user + "?api_key=" + apiKey)
.then(response => response.json())
.then(user => {
return fetch("https://" + region + ".api.riotgames.com/lol/match/v4/matchlists/by-account/" + user.accountId + "?api_key=" + apiKey)
})
.then(response => response.json())
.then(data => {
const matches = data.matches.slice(0, 10);
for (let match of matches) {
promises.push(fetch("https://" + region + ".api.riotgames.com/lol/match/v4/matches/" + match.gameId + "?api_key=" + apiKey).then(response => response.json()).then(game => {
return new Game(
game.teams[0].win,
"Win",
"Fail",
idFetch([game.participants[0].championId, game.participants[1].championId, game.participants[2].championId, game.participants[3].championId, game.participants[4].championId]),
idFetch([game.participants[5].championId, game.participants[6].championId, game.participants[7].championId, game.participants[8].championId, game.participants[9].championId])
);
}));
}
});
return await Promise.all(promises).then(dataArray => {
console.log(dataArray);
return dataArray;
});
}

解释器不会等待您的获取结束后再返回结果。尝试在第5行的fetch...之前添加await。但实际上它很难阅读,尽量不要将async/await语法与混合。然后,你会更容易理解=(

最新更新