Promise Chain not waiting for promises to resolve

2019-09-10 01:25发布

问题:

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?

回答1:

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