You should use a flow control library, like async
https://github.com/caolan/async
Or step
https://github.com/creationix/step
Edit: added an example with async
async.seriesparallel([
function(callback){
doRequest1(query, callback);
},
function(callback){
doRequest2(query2, callback);
},
function(callback){
doRequest3(query3, callback);
},
],
function(err, results){
if (err) {
renderError(err);
} else {
renderHTML(results[0], results[1], results[2]);
}
});
If you want to make each function run as series (wait for the previous function to complete), you may use async.series instead of async.parallel. If queries depend on the result of previous queries, you may use async.waterfall. If there is a complex dependency graph between queries, you may use async.auto.