在多个 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 行的 await 之前添加 fetch...。但实际上它很难阅读,尽量不要将 async/await 语法与 .then 混合使用,这样自己会更容易理解事情 =)>