Skip to main content
added 315 characters in body
Source Link
Philippe Plantier
  • 8.1k
  • 3
  • 29
  • 40

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.

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.series([
    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]);
    }
});

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.parallel([
    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.

Source Link
Philippe Plantier
  • 8.1k
  • 3
  • 29
  • 40

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.series([
    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]);
    }
});