yosiweinreb yosiweinreb - 1 month ago 8
Javascript Question

Correct pattern for multiway flows with Promises

So i have been playing with promises for the last few days, and just trying to convert some project, to use promises, but more than a few times i have encuntered this issue.


While reading articles and tutorials everything looks smooth and clean:

getDataFromDB()
.then(makeCalculatons)
.then(getDataFromDB)
.then(serveToClient)


But in reality, its not like that.
Programs have a lot of "if conditions" that changes the whole flow:

getDataFromCache(data).then(function(result){
if(result){
return result;
}else{
return getDataFromDB();
}
}).then(function(result){
if(result){
serveToClient() //this does not return a promise, so undefined returned...
}else{
return getDataFromWebService(); //this does return a promise,
}
}).then(function(result){
//i dont want to reach here if i already serveToClient()...
//so i basically have to check "if(result)" for all next thens
if(result){
//do more stuff
}
}).then(...


I have 2 major issues:


  1. I find myself adding alot of
    if
    conditions on the
    then
    callbacks.

  2. I am still getting into the next
    then
    callbacks, even if i already finished (
    serveToClient
    )




Am i following the correct pattern?

Answer

You can't avoid the if statements since that is required for your logic flow. You will have to branch your flow of control if you don't want to continue the promise chain in one part of the if. So if in some part of your second .then() handler, you don't want to go on to the third .then() handler, then you need to branch the logic like this and put subsequent .then() handlers inside the 2nd .then() handler in their own branch of the logic.

You can't just continue the top level branch because the only way to abort future .then() logic in the main chain is to either reject the promise (which you probably don't want to do) or add another if check in every .then() handler to decide whether it should be skipped or not (yuck).

So instead, you can branch the logic like this:

getDataFromCache().then(function(result){
    if(!result) {
        return getDataFromDB()
    } else {
        return result;
    }
}).then(function(result){
    // branch promise chain here into two separate branches
    if(result){
        // do not continue the promise chain here
        // call a synchronous operation
        serveToClient();
    } else {
        // continue promise chain here
        return getDataFromWebService().then(function(result) {
            if(result){
               //do more stuff
            }
        }).then(...);    // you can continue the promise chain here
    }
}).catch(function(err) {
    // process any errors here
});

You may find these other answers useful:

Understanding javascript promises; stacks and chaining

Is there a difference between promise.then.then vs promise.then; promise.then