Saras Arya
Saras Arya

Reputation: 3112

How to handle conditional callbacks using Promises(Bluebird) in NodeJS

I am currently trying to refactor the codebase that I have and want to have a more developer friendly codebase. Part 1 of that is changing callback to Promises. Currently, at some places we are using Async.waterfall to flatten the callback hell, which works for me. The remaining places where we couldn't was because they were conditional callbacks, That means different callback function inside if and else

if(x){
    call_this_callback()
}else{
    call_other_callback()
}

Now I use bluebird for promises in Node.JS and I can't figure out how to handle conditional callback to flatten the callback hell.

EDIT A more realistic scenario, considering I didn't get the crux of the issue.

var promise = Collection1.find({
    condn: true
}).exec()
promise.then(function(val) {
    if(val){
        return gotoStep2();
    }else{
        return createItem();
    }
})
.then(function (res){
    //I don't know which response I am getting Is it the promise of gotoStep2
    //or from the createItem because in both the different database is going
    //to be called. How do I handle this
})

Upvotes: 1

Views: 351

Answers (2)

jiajianrong
jiajianrong

Reputation: 928

Here is the answer to the promise branch: nested and unnested. Make the branches and don't join them together.

Upvotes: 0

iKoala
iKoala

Reputation: 880

There is no magic, you can easily chain promises with return inside a promise.

var promise = Collection1.find({
    condn: true
}).exec();

//first approach
promise.then(function(val) {
    if(val){
        return gotoStep2()
          .then(function(result) {
            //handle result from gotoStep2() here
          });
    }else{
        return createItem()
          .then(function(result) {
            //handle result from createItem() here
          });
    }
});

//second approach
promise.then(function(val) {
    return new Promise(function() {
        if(val){
            return gotoStep2()
        } else {
            return createItem();
        }
    }).then(function(result) {
        if (val) {
            //this is result from gotoStep2();
        } else {
            //this is result from createItem();
        }
    });
});

//third approach
promise.then(function(val) {
    if(val){
        return gotoStep2(); //assume return array
    } else {
        return createItem(); //assume return object
    }
}).then(function(result) {
    //validate the result if it has own status or type
    if (Array.isArray(result)) {
        //returned from gotoStep2()
    } else {
        //returned from createItem()
    }
    //you can have other validation or status checking based on your results
});

Edit: Update sample code because author updated his sample code. Edit: Added 3rd approach to help you understand promise chain

Upvotes: 2

Related Questions