JoeIsBlogging
JoeIsBlogging

Reputation: 185

Iterate over data and send as response

I am trying to take data, send that to an API, take data out of that and pass it on as a response. Currently I see the data in my terminal, but my response object is empty.

response

// Make API call to get the match data
var matches = await api.get(`${platform}1`, 'match.getMatchlist', player.accountId)

 //Check for errors and send 404 if errrs are found
if(matches.length  >0) {
    return res.status(404).json({
        message: 'No summoner found'
    })
}

//Due to large amount of data, splice entries to keep responses smaller and more manageable 
var splice = matches.matches.splice(0 , 2);

var matchData;

// Iterate over
splice.forEach((m) => {
    api.get(`${platform}1`, 'match.getMatch', m.gameId)
        .then((data) =>  {
            console.log(data.gameId)
            matchData = data.gameId;

        })

});

res.json({
    data: matchData
})

In my terminal, I get the expected data :

4114813378
4104452309

This shows that the API call is working and providing me with the correct ata but the data is lost between then and the res.json({})

I've tried pushing it to an array instead, but this also leaves my response eempty.

Upvotes: 0

Views: 82

Answers (1)

Neel Rathod
Neel Rathod

Reputation: 2111

You need to use Promise.all in the following manner;

userCtr.getGems = async (req, res) => {
  try {
    const matches = await api.get(`${platform}1`, 'match.getMatchlist', player.accountId);
    // Check for errors and send 404 if errrs are found
    if (matches && matches.length) {
      return res.status(404).json({
        message: 'No summoner found',
      });
    }

    // Due to large amount of data, splice entries to keep responses smaller and more manageable 
    const splice = matches.matches.splice(0, 2);
    const promises = [];
    splice.forEach((m) => {
      promises.push(api.get(`${platform}1`, 'match.getMatch', m.gameId));
    });
    const result = await Promise.all(promises);
    const gemIds = result.map((r) => { return r.gameId; });
    return res.staus(200).json({ data: gemIds });
  } catch (err) {
    logger.error(err);
    return res.status(500).json({ error: 'Internal server error' });
  }
};

Upvotes: 2

Related Questions