Search code examples
javascriptnode.jspromisebluebird

How to skip some then in promise(bluebird)?


Sample code:

Queues.findOne({_id: id})
.then(function(q) {
 var status = q.status;   
 //...
}).then(function(q) {
// A
}).then(function(q) {
// B
}).then(function(q) {
// C
}).then(function(q) {
// D
}).then(function(q) {
// E
}).then(function(q) {
// F
})

Depends on the status, the flow will different

if status is 1, A/B/C/D/E/F should be all executed.

if status is 2, C/D/E/F should be executed, how to skip A and B ?

if status is 3, E/F should be executed, how to skip A/B/C/D ?


Solution

  • You can use

    Queues.findOne({_id: id}).then(function(q) {
      var status = q.status;
      var x = Promise.resolve();
      var y = status <= 1 ? x.then(A).then(B) : x;
      var z = status <= 2 ? x.then(C).then(D) : y;
      return z.then(E).then(F);
    }