我在匹配获取上有一个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;
}
说明:我带来了一系列比赛,我经历了每场比赛。每场比赛都是一个承诺,包含主队和客队的链接。
那些match.home和match.away值也是团队的承诺,所以我将团队包装在Promise.all中,以便在将值分配给字符串类型值之前解析:match.homeTeam和match.awayTeam。 / p>
问题: 当我调用函数时:
this.updateTableInformation(match);
它使用match.homeTeam和match.awayTeam,但当它到达时,团队承诺尚未解决,因此match.homeTeam = undefined;
问题:
如何在调用 updateTableInformation(匹配)之前等待团队承诺(以及上层匹配承诺)??
我正在使用es6,es2016
答案 0 :(得分:2)
我将团队包装在Promise.all中,以便在将值分配给匹配之前解决。
不,因为将.then(…)
直接链接到承诺就足够了。
当它到达函数
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
以便您获得一系列承诺以供使用:
matches => Promise.all(matches.map(updateMatch))