我有一個比賽一個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。
問題: 當我調用該函數:
this.updateTableInformation(match);
它採用match.homeTeam和match.awayTeam但是當它到達那裏,球隊的承諾尚未解決,因此match.homeTeam =未定義;
問題:
我如何可以等待球隊的承諾(和上一級賽諾)調用updateTableInformation(比賽)之前得到解決;?
我使用ES6,es2016
爲什麼你叫'Promise.all'陣列上有一個承諾? – Bergi
^是的,看起來你需要將你的'teamService.getTeam()'調用組合在同一個'Promise.all'數組/調用中。 – matmo
@Bergi說實話,我的知識有限,我使用Promise.all,因爲它是我知道它等待它解決的問題,而且只包含一個元素就是確保順序。每場比賽我都有兩支球隊,然後是球隊[0],球隊[1],但是有時候這些數據是相反的。 –