Node.js 基于条件逻辑调用Q承诺
以下是我的情况Node.js 基于条件逻辑调用Q承诺,node.js,promise,q,Node.js,Promise,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 ch
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
}
如果abc为true
调用异步func1,func2
其他的
调用异步func1
函数测试():Q.Promise{
国际单项体育联合会(abc)
Q.all([func1,func2])
其他的
Q.all([func1])
//如果失败,则在链中一路抛出拒绝原因
}
if
和else
子句来完成,有没有更好的方法有条件地调用promise错误
我会将承诺放入数组中,并根据条件追加新的承诺:
function test(): Q.Promise<Boolean[]> {
const promises = [func1()]
if (abc) promises.push(func2())
return Q.all(promises)
}
函数测试():Q.承诺{
常量承诺=[func1()]
if(abc)promises.push(func2())
返回Q.all(承诺)
}
我稍微更正了类型签名,因为
Q.all
使用来自每个底层承诺的值数组(在您的例子中是布尔值)进行解析。您还需要调用func1
和func2
。最后,不要忘记从test
函数返回。您实际上已经非常接近了:
function test() {
if(abc)
return Q.all([func1(),func2()])
else
return func1();
}
test().then(() => {
// do whatever
}).catch(err => console.log(err));
确保您始终返回承诺,因为它们不会被其他方式束缚。如果其中一个
承诺被拒绝,会发生什么情况,我将如何抛出该错误。我正在努力学习Q.promises
,所以如果这是一个愚蠢的问题,请原谅:)您不需要明确地抛出。如果其中一个函数抛出或返回被拒绝的承诺,那么Q.all
也将为您拒绝,并且错误将自动冒泡到Q.all错误处理程序:test().then(function(){console.log('all fine'))))).catch(function(error){console.log('something gourg')}
。