2017-06-20 160 views
0

我有一個比賽一個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

+0

爲什麼你叫'Promise.all'陣列上有一個承諾? – Bergi

+0

^是的,看起來你需要將你的'teamService.getTeam()'調用組合在同一個'Promise.all'數組/調用中。 – matmo

+0

@Bergi說實話,我的知識有限,我使用Promise.all,因爲它是我知道它等待它解決的問題,而且只包含一個元素就是確保順序。每場比賽我都有兩支球隊,然後是球隊[0],球隊[1],但是有時候這些數據是相反的。 –

回答

1

我裹在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等到所有T他在迭代數組中的匹配被實現。不要使用.forEach,使用.map讓你回來的承諾數組使用方法:

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

謝謝你這個伎倆!而且我學習的不僅僅是我對這個問題的期待。謝謝! –