最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditional then in promises (bluebird) - Stack Overflow

programmeradmin3浏览0评论

What I want to do

getFoo()
  .then(doA)
  .then(doB)
  .if(ifC, doC)
  .else(doElse)

I think the code is pretty obvious? Anyway:

I want to do call a promise when a specific condition (also a promise) is given. I could probably do something like

getFoo()
  .then(doA)
  .then(doB)
  .then(function(){
    ifC().then(function(res){
    if(res) return doC();
    else return doElse();
  });

But that feels pretty verbose.

I'm using bluebird as promise library. But I guess if there is something like that it'll be the same in any promise library.

What I want to do

getFoo()
  .then(doA)
  .then(doB)
  .if(ifC, doC)
  .else(doElse)

I think the code is pretty obvious? Anyway:

I want to do call a promise when a specific condition (also a promise) is given. I could probably do something like

getFoo()
  .then(doA)
  .then(doB)
  .then(function(){
    ifC().then(function(res){
    if(res) return doC();
    else return doElse();
  });

But that feels pretty verbose.

I'm using bluebird as promise library. But I guess if there is something like that it'll be the same in any promise library.

Share Improve this question asked Dec 14, 2015 at 16:10 boopboop 7,78715 gold badges58 silver badges100 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Based on this other question, here's what i came up with for an optional then:

Note: if your condition function really needs to be a promise, look at @TbWill4321's answer

answer for 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

improved answer from @jacksmirk for conditional 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

You don't need to have nested .then calls, since it seems like ifC returns a Promise anyways:

getFoo()
  .then(doA)
  .then(doB)
  .then(ifC)
  .then(function(res) {
    if (res) return doC();
    else return doElse();
  });

You could also do some legwork up front:

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

I think you are looking for something like this

An example with your code:

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

The elements in the condition must be defined before starting the chain.

发布评论

评论列表(0)

  1. 暂无评论