I have a Node.js application in which you can call several functions depending on several factors, but after the last callback, only one last function is called.
This is a simplified version of what I got:
if(foo === bar){ function1(arg1, function(val1){ doWhatever(val1, function(){ res.end("Finished"); }); }); }else if(foo === baz){ function2(arg2, function(val2){ doWhatever(val2, function(){ res.end("Finished"); }); }); }else{ function3(arg3, function(val3){ doWhatever(val3, function(){ res.end("Finished"); }); }); }
And here is what I do:
var finished = false; if(foo === bar){ function1(arg1, function(val1){ result = val1; finished = true; }); }else if(foo === baz){ function2(arg2, function(val2){ result = val2; finished = true; }); }else{ function3(arg3, function(val3){ result = val3; finished = true; }); } var id = setInterval(function(){ if(finished === true){ clearInterval(id); doWhatever(result, function(){ res.end("Finished"); }); } }, 100);
I suppose this can be simplified using promises, however I'm not sure how to implement it.
source share