有条件的承诺(蓝鸟)

Conditional then in promises (bluebird)

本文关键字:蓝鸟 承诺 有条件      更新时间:2023-09-26

我想做什么

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();
  });

但这感觉相当冗长。

我用蓝鸟作为承诺图书馆。但我想,如果有这样的东西,在任何promise库中都是一样的。

基于另一个问题,以下是我提出的可选选项:

注意:如果你的条件函数真的需要是一个承诺,请查看@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

@jacksmark对条件then() 的改进答案

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

编辑:我建议你看看蓝鸟关于在这里安装promise.if() 的讨论

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

我想你正在寻找类似的东西

代码示例:

getFoo()
  .then(doA)
  .then(doB)
  .then(condition ? doC() : doElse());

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