Promise Chain 在结束之前不等待 Promise 解决 [英] Promise Chain not waiting for promises to resolve before ending

查看:54
本文介绍了Promise Chain 在结束之前不等待 Promise 解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图简化这些:

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

据我了解 Promise.all 应该等到 playerStatsPromise 中包含的所有承诺都解决了吗?

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

那么为什么 All DoneGrab Done 之前完成?

So why does All Done finish before Grab Done?

推荐答案

您似乎在构建数组 playerStatsPromise 时引用了未定义的变量 data2.而是使用 map 来构建您的数组,因为这将返回承诺:

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

这篇关于Promise Chain 在结束之前不等待 Promise 解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆