Search code examples
javascriptasynchronousfetchfor-of-loop

Using a fetch within a for loop within several fetch requests


Ok guys, I am really stuck on what to do here to make sure that everything executes in order. It feels like im missing an await or something else really simple but I really cant seem to piece together why my return await doesnt just return AFTER all the other fetches are done.

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;
    });
}

Solution

  • Interpreter does not wait your fetch to end before returning result. Try to add await before fetch... on line 5. But actually its pretty hard to read, try to not mix async/await syntax with .then, will be easier for yourself to understand things =)