有条件的 then in promise (bluebird)

boo*_*oop 4 javascript node.js promise

我想做的事

getFoo()
  .then(doA)
  .then(doB)
  .if(ifC, doC)
  .else(doElse)
Run Code Online (Sandbox Code Playgroud)

我认为代码很明显?反正:

我想在给出特定条件(也是一个承诺)时调用一个承诺。我可能会做类似的事情

getFoo()
  .then(doA)
  .then(doB)
  .then(function(){
    ifC().then(function(res){
    if(res) return doC();
    else return doElse();
  });
Run Code Online (Sandbox Code Playgroud)

但这感觉很冗长。

我使用 bluebird 作为承诺库。但我想如果有类似的东西,它在任何承诺库中都是一样的。

Xel*_*tor 5

基于另一个问题,这是我想出的可选选项:

注意:如果您的条件函数确实需要成为承诺,请查看@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
Run Code Online (Sandbox Code Playgroud)

来自@jacksmirk 的有条件的改进答案 then()

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

编辑:我建议你看一下 Bluebird 关于在这里的讨论promise.if()


TbW*_*321 4

您不需要嵌套调用.then,因为它似乎无论如何ifC都会返回Promise

getFoo()
  .then(doA)
  .then(doB)
  .then(ifC)
  .then(function(res) {
    if (res) return doC();
    else return doElse();
  });
Run Code Online (Sandbox Code Playgroud)

您还可以预先做一些跑腿工作:

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 ));
Run Code Online (Sandbox Code Playgroud)