user4815703
user4815703

Reputation:

array displays as empty after using .push() via loop?

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

Upvotes: 1

Views: 1611

Answers (1)

Ovidiu Dolha
Ovidiu Dolha

Reputation: 5413

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

Upvotes: 1

Related Questions