1

I am not sure if its todo with how i am trying to save the data to the array but using console.log the array seems to be empty and thus cannot display data from it. Please see if my current code is properly structured:

I would like to confirm matchIds actually contains an array of data:

var getGameData = function (matchIds) {
console.log('Executing getGameData');
return new Promise(function (resolve, reject) {
    var gameData = [];
    for (var i = 0; i < matchIds.length; i++) {
      lolapi.Match.get(matchIds[i], function (error, gamedata) {
          if (error) {
              return reject(error);
          }
          if (gamedata) {
              gameData.push(gamedata);
          }
      });
      if (i === 9) {
        resolve(gameData);
      }
    }
});
};
  • Where are you logging it? After the resolve I presume? – Erik Jan 10 '17 at 09:21
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Jan 10 '17 at 09:26

1 Answers1

1

You have another portion of async code in your proimse body (well I assume it is async based on your results):

  lolapi.Match.get(matchIds[i], function (error, gamedata) { ...

Therefore at the end of the loop (for), your gameData.push(gamedata); instructions (from multiple callbacks) will not have been exectued so resolve(gameData); will be [].

You can use a Promise.all approach:

var gameDataPromises = [];
for (var i = 0; i < matchIds.length; i++) {
  gameDataPromises.push(new Promise(function(res, rej) { lolapi.Match.get(matchIds[i], function (error, gamedata) {
      if (error) {
          rej(error);
      }
      if (gamedata) {
          res(gamedata);
      }
  })}));
}

Promise.all(gameDataPromises).then(resolve).catch(reject)

This will effectively capture all your lolapi.Match.get in a single Promise that waits for all of them - if one fails the reject of your main promise will be called - if all succeed, then the data from all of the inner calls will be passed to the resolve of your main promise as an array (what you were expecting i guess).

Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30
  • Thanks mate i guess i have to understand promises more. I have always done it using callbacks haha –  Jan 11 '17 at 20:54