title: Node MySql Callback for Multiple Queries
body: <p>I ran into an issue whilst attempting to create the logic to add rows to a new table I made on my MySql database. When adding a row I need to query the database 4 times to check other rows and to then add the correct value to the new row. I am using node.js and the mysql module to accomplish this. While coding I ran into a snag, the code does not wait for the 4 queries to finish before inserting the new row, this then gives the values being found a value of 0 every time. After some research I realize a callback function would be in order, looking something like this:<br></p>
  
  <pre><code>var n = 0;
  connection.query("select...", function(err, rows){
      if(err) throw err;
      else{
          if(rows.length === 1) ++n;
      }
      callback();
  });
  
  function callback(){
      connection.query("insert...", function(err){
           if(err) throw err;
      });
  }
  </code></pre>
  
  <p>Note: The select queries can only return one item so the if condition should not effect this issue.<br><br></p>
  
  <p>A callback function with only one query to wait on is clear to me, but I become a bit lost for multiple queries to wait on. The only idea that I had would be to create another variable that increments before the callback is called, and is then passed in the callback function's arguments. Then inside the callback the query could be encapsulated by an if statement with a condition of this being the variable equaling the number of queries that need to be called, 4 for my purposes here. I could see this working but wasn't sure if this sort of situation already has a built in solution or if there are other, better, solutions already developed.</p>