Promises (bluebird)中的条件语句

6

What I want to do

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库中都会有类似的东西。

3个回答

5

基于这个问题的答案,以下是我为可选的then函数想出来的代码:

注意:如果你的条件函数确实需要一个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的改进答案,针对条件then()

getFoo()
  .then(doA)
  .then(doB)
  .then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()

编辑:我建议你查看Bluebird的讨论,了解promise.if()的情况这里


4

您不需要嵌套.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 ));

2
我觉得你想要的是类似于这个的东西。
下面是带有您代码示例的实例:
getFoo()
  .then(doA)
  .then(doB)
  .then(condition ? doC() : doElse());

条件中的元素必须在启动链之前定义。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接