有条件的承诺(蓝鸟)
我想做的事
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(); });
但是,这感觉相当详细。
我使用蓝鸟作为承诺库。 但是我猜如果有这样的事情,在任何承诺库里都是一样的。
你不需要嵌套的。然后调用,因为它似乎如果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());
条件中的元素必须在启动链之前进行定义。
基于这个其他问题 ,这是我想出了一个可选的然后:
注意:如果你的条件函数真的需要承诺,请看@TWWill4321的答案
then()
select答案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
then()
改进了@jacksmirk的答案
getFoo() .then(doA) .then(doB) .then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()
编辑:我build议你看看有一个
promise.if()
这里的蓝鸟的讨论