【问题标题】:Conditional then in promises (bluebird)有条件的然后在承诺中(蓝鸟)
【发布时间】:2016-03-20 04:53:18
【问题描述】:

我想做的事

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 库中都会是一样的。

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    基于this other question,这是我当时想出的可选内容:

    注意:如果您的条件函数确实需要成为一个承诺,请查看@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
    

    @jacksmirk 改进了 条件 then()

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

    编辑:我建议你看看 Bluebird 关于拥有 promise.if() HERE 的讨论

    【讨论】:

      【解决方案2】:

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

      您的代码示例:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2014-02-13
          • 2015-09-15
          • 1970-01-01
          • 1970-01-01
          • 2017-10-10
          • 1970-01-01
          • 2014-11-06
          • 2015-09-06
          • 2015-02-13
          相关资源
          最近更新 更多