Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird - how to break promise chain early

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())?

like image 497
Jonah Avatar asked May 09 '16 08:05

Jonah


1 Answers

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
});
like image 122
Shanoor Avatar answered Nov 15 '22 18:11

Shanoor