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

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate i guess i have to understand promises more. I have always done it using callbacks haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.