2016-08-24 244 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)); 

确保你总是返回的承诺,因为他们没有得到链接,否则。