在多个提取请求中的 for 循环中使用提取
Using a fetch within a for loop within several fetch requests
好的,我真的不知道该怎么做才能确保一切按顺序执行。感觉我错过了一个 await 或其他非常简单的东西,但我真的无法拼凑为什么我的 return await 不只是 return 在所有其他提取完成之后。
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 语法与 .then 混合使用,这样您自己会更容易理解事情 =)
好的,我真的不知道该怎么做才能确保一切按顺序执行。感觉我错过了一个 await 或其他非常简单的东西,但我真的无法拼凑为什么我的 return await 不只是 return 在所有其他提取完成之后。
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 语法与 .then 混合使用,这样您自己会更容易理解事情 =)