我想做的是
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();
});
但这感觉相当冗长。
我正在使用bluebird作为promise库。但我猜,如果有这样的东西,它在任何promise库中都是一样的。
发布于 2017-08-24 22:57:31
基于this other question,这是我想出的一个可选选项:
注意:如果你的条件函数真的需要一个promise,看看@TbWill4321的答案
针对optional 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
改进了@jacksmirk对conditional then()
的回答
getFoo()
.then(doA)
.then(doB)
.then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()
EDIT:我建议您看看Bluebird关于拥有
promise.if()
HERE
的讨论
发布于 2015-12-15 00:13:43
您不需要嵌套的.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 ));
发布于 2016-11-24 23:45:02
我想你正在寻找像this这样的东西
下面是你的代码的例子:
getFoo()
.then(doA)
.then(doB)
.then(condition ? doC() : doElse());
必须在启动链之前定义条件中的元素。
https://stackoverflow.com/questions/34271606
复制相似问题