根据条件逻辑调用Q Promise
Calling Q Promise on the basis of conditional logic
以下是我的情况
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
?
我会将 promise 放入数组中,并根据条件添加新的:
function test(): Q.Promise<Boolean[]> {
const promises = [func1()]
if (abc) promises.push(func2())
return Q.all(promises)
}
我稍微更正了类型签名,因为 Q.all
使用来自每个基础承诺的 array 值(在您的情况下为布尔值)解析。您还需要调用 func1
和 func2
。最后,不要忘记从 test
函数 return。
你实际上已经很接近了:
function test() {
if(abc)
return Q.all([func1(),func2()])
else
return func1();
}
test().then(() => {
// do whatever
}).catch(err => console.log(err));
确保你始终return 承诺,否则它们不会被链接。
以下是我的情况
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
?
我会将 promise 放入数组中,并根据条件添加新的:
function test(): Q.Promise<Boolean[]> {
const promises = [func1()]
if (abc) promises.push(func2())
return Q.all(promises)
}
我稍微更正了类型签名,因为 Q.all
使用来自每个基础承诺的 array 值(在您的情况下为布尔值)解析。您还需要调用 func1
和 func2
。最后,不要忘记从 test
函数 return。
你实际上已经很接近了:
function test() {
if(abc)
return Q.all([func1(),func2()])
else
return func1();
}
test().then(() => {
// do whatever
}).catch(err => console.log(err));
确保你始终return 承诺,否则它们不会被链接。