Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional then in promises (bluebird)

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.

like image 657
boop Avatar asked Dec 18 '22 21:12

boop


1 Answers

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

like image 94
Xeltor Avatar answered Dec 22 '22 11:12

Xeltor