在条件逻辑的基础上调用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 }
- 如图所示,它可以使用
if
和else
子句完成,有没有更好的方法来有条件地调用promise? - 如何抛出
error from any one of the promises
?
我会把数组中的承诺,并根据条件追加新的:
function test(): Q.Promise<Boolean[]> { const promises = [func1()] if (abc) promises.push(func2()) return Q.all(promises) }
我纠正了一些types的签名,因为Q.all
从每个基础承诺的数组值(布尔在你的情况)解决。 您还需要调用func1
和func2
。 最后,不要忘记从test
function返回。
你其实已经很近了:
function test() { if(abc) return Q.all([func1(),func2()]) else return func1(); } test().then(() => { // do whatever }).catch(err => console.log(err));
确保你总是返回承诺,因为他们不被链接。