Reputation: 18848
Below is my condition
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
}
if
and else
clause, is there a better way to call promise conditionally?error from any one of the promises
?Upvotes: 1
Views: 149
Reputation: 3342
You are actually pretty close already:
function test() {
if(abc)
return Q.all([func1(),func2()])
else
return func1();
}
test().then(() => {
// do whatever
}).catch(err => console.log(err));
Make sure you always return the promises as they don't get chained otherwise.
Upvotes: 0
Reputation: 193261
I would put promises in array and append new one depending on condition:
function test(): Q.Promise<Boolean[]> {
const promises = [func1()]
if (abc) promises.push(func2())
return Q.all(promises)
}
I corrected type signature a little, because Q.all
resolves with array of values (Boolean in your case) from each underlying promises. You also need to call func1
and func2
. And finally, don't forget to return from test
function.
Upvotes: 1