我想做什么
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库中都是一样的。
基于另一个问题,以下是我提出的可选选项:
注意:如果你的条件函数真的需要是一个承诺,请查看@TbWill4321的答案
可选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
@jacksmark对条件then()
的改进答案
getFoo()
.then(doA)
.then(doB)
.then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()
编辑:我建议你看看蓝鸟关于在这里安装
promise.if()
的讨论
您不需要嵌套.then
调用,因为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());
在启动链之前,必须定义条件中的元素。