2016-08-24 265 views
1

的基礎上調用Q無極下面是我的病情條件邏輯

if abc is true 
    call async func1, func2 
else 
    call async func1 

function test(): Q.Promise<boolean> { 
    if(abc) 
     Q.all([func1,func2]) 
    else 
     Q.all([func1]) 
    //if failed throw reject reason all the way in the chain 
} 
  1. 如圖所示,它可以使用ifelse條款來完成,有沒有更好的方式來有條件地承諾?
  2. 如何丟回error from any one of the promises

回答

1

我把承諾在陣列並追加新的視病情:

function test(): Q.Promise<Boolean[]> { 
    const promises = [func1()] 
    if (abc) promises.push(func2()) 
    return Q.all(promises) 
} 

我糾正類型簽名一點,因爲Q.all數組值(布爾你的情況)從解析每個基礎承諾。您還需要致電func1func2。最後,不要忘記從test函數返回。

+0

如果其中一個'promise'被「拒絕」會怎麼樣,並且我會如何一直向上拋出該「錯誤」。我試圖學習'Q.promises',所以如果這是個愚蠢的問題,請原諒:) – Reddy

+0

你不需要明確地拋出。如果其中一個函數拋出或返回被拒絕的promise,那麼'Q.all'也會拒絕你,並且錯誤會自動冒泡到Q.all錯誤處理器:'test()。then(function(){console.log('所有罰款')})。catch(function(error){console.log('something went wrong')})'。 – dfsq

0

你實際上是相當已近:

function test() { 
    if(abc) 
     return Q.all([func1(),func2()]) 
    else 
     return func1(); 
} 
test().then(() => { 
    // do whatever 
}).catch(err => console.log(err)); 

確保你總是返回的承諾,因爲他們沒有得到鏈接,否則。