我想做什么
getFoo()
.then(doA)
.then(doB)
.if(ifC, doC)
.else(doElse)
我觉得代码很明显?无论如何:
我想在给出特定条件(也是 promise )时调用 promise 。我可能会做类似的事情
getFoo()
.then(doA)
.then(doB)
.then(function(){
ifC().then(function(res){
if(res) return doC();
else return doElse();
});
但这感觉很冗长。
我正在使用 bluebird 作为 promise 库。但我想如果有类似的东西,它在任何 promise 库中都是一样的。
最佳答案
基于 this other question ,这就是我想出的可选方案:
Note: if your condition function really needs to be a promise, look at @TbWill4321's answer
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 对条件 then()
getFoo()
.then(doA)
.then(doB)
.then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()
EDIT: I suggest you have a look at Bluebird's discussion on having a
promise.if()
HERE
关于javascript - 有条件的然后在 promise 中( bluebird ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271606/