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:
- I find myself adding alot of
if
conditions on thethen
callbacks. - I am still getting into the next
then
callbacks, even if i already finished (serveToClient
)
Am i following the correct pattern?