【问题标题】:How can I wait for two promises within a promise to be resolved before calling a function?在调用函数之前,如何等待一个 Promise 中的两个 Promise 被解决?
【发布时间】:2017-06-20 16:50:38
【问题描述】:

我有一个用于执行此操作的匹配项的 forEach:

matches => {
            matches.forEach(match => {
              Promise.all([this.teamService.getTeam(match._links.homeTeam.href)])
                  .then( team => { 
                    match.homeTeam = team[0].teamName;
                  }
                );
              Promise.all([this.teamService.getTeam(match._links.awayTeam.href)])
                  .then( team => { 
                    match.awayTeam = team[0].teamName;
                  }
                );
              this.updateTableInformation(match);
            });
            return matches;
          }

解释:我引入了一系列匹配项,然后遍历每一场匹配项。每场比赛都是一个 Promise,其中包含指向主队和客队的链接。

这些 match.home 和 match.away 值也是球队的承诺,所以我将球队包装在 Promise.all 中,以便在将值分配给字符串类型值之前解决它:match.homeTeam 和 match.awayTeam。

问题: 当我调用函数时:

  this.updateTableInformation(match);

它使用 match.homeTeam 和 match.awayTeam,但是当它到达那里时,团队承诺尚未解决,因此 match.homeTeam = undefined;

问题

如何在调用 updateTableInformation(match); 之前等待团队承诺(和上层比赛承诺)得到解决?

我正在使用 es6、es2016

【问题讨论】:

  • 你为什么要在一个只有一个承诺的数组上调用Promise.all?!
  • ^ 是的,看来您需要将您的 teamService.getTeam() 调用组合在同一个 Promise.all 数组/调用中。
  • @Bergi 老实说我的知识有限,我使用了 Promise.all 因为我知道它是如何等待解决的,并且只包装一个元素是为了确保顺序。每场比赛我都有两支球队,然后是 team[0], team[1],但有时值是相反的。
  • 请注意,Promise.all 不会阻止 JavaScript 继续执行其余的函数。只有“thens”中的代码在等待。
  • 建议您的语言更精确。你不能有“承诺中的承诺”。事实上,除了某种内部状态之外,“在一个承诺中”根本没有任何东西。

标签: angular typescript ecmascript-6 es6-promise


【解决方案1】:

我将团队包装在 Promise.all 中,以便在将值分配给匹配之前解决它。

不,只需将 .then(…) 直接链接到 Promise 就足够了。

当它到达函数this.updateTableInformation(match)时,团队承诺尚未解决

是你应该使用Promise.all的地方,等待你需要等待的所有承诺,并在返回的承诺的then回调中使用它们的结果:

function updateMatch(match) {
    const homePromise = this.teamService.getTeam(match._links.homeTeam.href).then(team => {
        match.homeTeam = team[0].teamName;
    });
    const awayPromise = this.teamService.getTeam(match._links.awayTeam.href).then(team => {
        match.awayTeam = team[0].teamName;
    });
    return Promise.all([homePromise, awayPromise]).then(() => {
        this.updateTableInformation(match);
    });
}

还可以使用Promise.all 等待迭代数组中的所有匹配项都完成。不要使用.forEach,使用.map,这样你就可以得到一系列要使用的promise:

matches => Promise.all(matches.map(updateMatch))

【讨论】:

  • 谢谢你成功了!而且我从这个问题中学到的东西超出了我的预期,呵呵。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-05-28
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多