0

I've tried to simplify these down a bit:

      passData.savedDBGames.forEach((gameInfo) => {
        return new Promise((resolve, reject) => {
          stats.getPlayersStats(gameInfo.fixtureID).then((playerStats) => {
             playerStatsPromise.push(playerStats);
             console.info('Grab Done');
             resolve();
           });
        });
      });

      Promise.all(playerStatsPromise)
        .then(function () {
          console.info('All Done');
          app.io.emit('admin', 'Admin: done');
          resolve(passData);
        });

To my understanding Promise.all should wait until all of the promises contained in playerStatsPromise have resolved?

So why does All Done finish before Grab Done?

enter image description here

Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • Your code doesn't make sense. `forEach` in particular is meant to cause side-effects, however you're returning a new Promise inside of it. – aaaaaa Dec 15 '16 at 21:02
  • `data2` was from the bigger promise chain. @aaaaaa I did that to try and force a Promise to be returned, thats just me experimenting. – Jamie Hutber Dec 15 '16 at 21:03
  • 1
    You should never create a `new Promise` if you use a promise inside of it, you should use those directly as return. In addition you will break your code in the case where `getPlayersStats` fails because you never handle the rejecting case of the chain your start with `getPlayersStats`. – t.niese Dec 15 '16 at 21:11
  • Yes, I really need to write my catches. Thanks :D – Jamie Hutber Dec 15 '16 at 23:18

1 Answers1

2

You seem to reference an undefined variable data2 when building your array playerStatsPromise. Instead use map to build your array, since that will return the promises:

  var playerStatsPromise = passData.savedDBGames.map((gameInfo) => {
    return new Promise((resolve, reject) => {
      stats.getPlayersStats(gameInfo.fixtureID).then((playerStats) => {
         console.info('Grab Done');
         resolve();
       });
    });
  });

  Promise.all(playerStatsPromise)
    .then(function () {
      console.info('All Done');
      app.io.emit('admin', 'Admin: done');
      resolve(passData);
    });

And if this is all you do in your first code block, you could simplify to:

  var playerStatsPromise = passData.savedDBGames
      .map(gameInfo => stats.getPlayersStats(gameInfo.fixtureID));

  Promise.all(playerStatsPromise)
    .then(function () {
      console.info('All Done');
      app.io.emit('admin', 'Admin: done');
      resolve(passData);
    });
trincot
  • 317,000
  • 35
  • 244
  • 286