Search code examples
node.jsunderscore.jsnode-mysql

executing an array of queries before a callback


What i want to do is loop through an object of sql queries, execute them one by one while retrieving results and then call the callback after everything is finished. Here is the code:

    _.each(fieldValSQL, function(sql, fieldKey) {
      conn.query(sql, function(err, result) {
        fields[fieldkey] = result;
      }); 
    });

    //this should execute last
    cb();

Solution

  • Try this. After each query finishes, runs a function that checks if all queries has successfully executed, and if so, then does the callback.

    var totalQueries = fieldValSQL.length;
    var doneQueries = 0;
    
    var doneChecker = function() {
      if (totalQueries == doneQueries) {
        //this should execute last
        cb();
      }
    }
    
    _.each(fieldValSQL, function(sql, fieldKey) {
      conn.query(sql, function(err, result) {
        fields[fieldkey] = result;
        doneQueries++;
        doneChecker();
      }); 
    });