8
PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        return ?? //break promise early - don't perform next then()
    else
        return PromiseB()
}).then(function(dataB){
    console.log(dataB)
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
})

How can the above code be modified to break early (skip the 2nd then())?

Jonah
  • 2,040
  • 7
  • 29
  • 32

1 Answers1

10

Bluebird allows to cancel a promise:

var Promise = require('bluebird');
Promise.config({
    // Enable cancellation
    cancellation: true,
});

// store the promise
var p = PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        p.cancel(); // cancel it when needed
    else
        return PromiseB();
}).then(function(dataB){
    console.log(dataB);
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
});
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • Doesn't p need to be defined before being invoked though? When p is first invoked here, it doesn't look like it's defined yet. – Jonah May 09 '16 at 10:33
  • @Jonah We are in async environment, the function is not executed right away (it is on the next tick), by the time it is, `p` is defined. – Shanoor May 09 '16 at 10:42
  • isn't `p` set to the value of that last statement in the chain - the `catch` in this case? However, the catch is not executed until after `p.cancel()` is called – Jonah May 09 '16 at 10:47
  • Promise methods will always synchronously return the same promise to guaranty that you can continue to chain with more methods. so the value of the chain call is always the same promise. Example `const p = Promise.then(...).then();` returns a promise. and then you can do: `p.then(...).catch(...);` – SimoAmi Jan 26 '17 at 06:15