You cannot escape if
, as this is necessary for your logical stream. You will need to control the flow of the branch if you do not want to continue the promise chain in one part of the if
. Therefore, if in some part of your second .then()
handler you do not want to go to the third .then()
handler, then you need to separate the logic as follows and put the subsequent .then()
handlers in the 2nd .then()
in its branch of logic.
You cannot simply continue the top-level branch, because the only way to break the future .then()
logic in the main chain is to either reject the promise (which you probably do not want to make), or add another if
check each .then()
handler to decide whether to skip it or not (yuck).
So you can split the logic as follows:
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 helpful:
Understanding javascript promises; stacks and chain
Is there a difference between a promise. then .then vs prom.then; promise.then
FYI, you can reorganize the above code to be a little more concise, for example:
getDataFromCache().then(function(result) { if (result) serveToClient(); } else { return getDataFromWebService().then(function(result) { if(result){
source share