Danmoreng Danmoreng - 1 month ago 7
Javascript Question

How to fit JSON.parse into Promise.all?

I got this code to retrieve a batch of matches from Riot Games League of Legends API:

const matches = await Promise.all(matchlist.matches.map(function(match){
return qRequest(server, "/match/v3/matches/" + match.gameId);
}));


The return value is a JSON formatted String. So
matches
ends up beeing an array of JSON Strings. I need the JSON parsed though, so that matches is an array of objects.

I just can't wrap my head around how to fit JSON.parse in here?

Answer Source

You can apply Array#map to matches

let matches = ... ;
matches = matches.map(json => JSON.parse(json));

or call JSON.parse inline:

const matches = await Promise.all(matchlist.matches.map(function(match){
  return qRequest(server, "/match/v3/matches/" + match.gameId)
    .then(json => JSON.parse(json));
}));