Javascript 有条件的承诺(蓝鸟)
我想做什么Javascript 有条件的承诺(蓝鸟),javascript,node.js,promise,Javascript,Node.js,Promise,我想做什么 getFoo() .then(doA) .then(doB) .if(ifC, doC) .else(doElse) 我觉得代码很明显?无论如何: 当一个特定的条件(也是一个承诺)被给出时,我想做一个承诺。我可能会做类似的事情 getFoo() .then(doA) .then(doB) .then(function(){ ifC().then(function(res){ if(res) return doC(); else r
getFoo()
.then(doA)
.then(doB)
.if(ifC, doC)
.else(doElse)
我觉得代码很明显?无论如何:
当一个特定的条件(也是一个承诺)被给出时,我想做一个承诺。我可能会做类似的事情
getFoo()
.then(doA)
.then(doB)
.then(function(){
ifC().then(function(res){
if(res) return doC();
else return doElse();
});
但这感觉相当冗长
我用蓝鸟作为承诺图书馆。但是我想如果有这样的东西,在任何promise库中都是一样的。你不需要嵌套
。然后调用,因为它看起来像ifC
返回一个promise
:
getFoo()
.then(doA)
.then(doB)
.then(ifC)
.then(function(res) {
if (res) return doC();
else return doElse();
});
你也可以先做一些腿部运动:
function myIf( condition, ifFn, elseFn ) {
return function() {
if ( condition.apply(null, arguments) )
return ifFn();
else
return elseFn();
}
}
getFoo()
.then(doA)
.then(doB)
.then(ifC)
.then(myIf(function(res) {
return !!res;
}, doC, doElse ));
我想你在找类似的东西
下面是一个代码示例:
getFoo()
.then(doA)
.then(doB)
.then(condition ? doC() : doElse());
在启动链之前,必须定义条件中的元素。基于,下面是我为可选条件提出的建议:
注意:如果您的条件函数真的需要是一个承诺,请查看@TbWill4321的答案
回答可选的then()
@jacksmirk对条件的then()的改进答案
编辑:我建议你看看蓝鸟关于承诺的讨论。如果()
getFoo()
.then(doA)
.then(doB)
.then((b) => { ifC(b) ? doC(b) : Promise.resolve(b) }) // to be able to skip doC()
.then(doElse) // doElse will run if all the previous resolves
getFoo()
.then(doA)
.then(doB)
.then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()