title: JavaScript Sequential / Synchronous Callback Functions Inside For Loop
body: <p>I currently have this situation...</p>
  
  <pre><code>function loop (num1, callback) {
      for (i = 0; i &lt; num1; i++) {
          console.log("loop count: " + i);
          callback();
      }
  }
  </code></pre>
  
  <p>Which is currently outputting the following sample results:</p>
  
  <pre><code>loop count: 1
  loop count: 2
  loop count: 3
  ...
  loop count: num1 - 1
  callback output 1
  callback output 2
  callback output 3
  ...
  callback output num1 - 1
  </code></pre>
  
  <p>What I would like it to do is wait until each callback has finished executing and outputting its result before moving onto the next item in the loop. i.e. as per the sample output below:</p>
  
  <pre><code>loop count: 1
  callback output 1
  loop count: 2
  callback output 2
  loop count: 3
  callback output 3
  ...
  loop count: num1 - 1
  callback output num1 - 1
  </code></pre>
  
  <p>Does anyone know how I can achieve this sequential / synchronous mode of operation in my function?</p>
  
  <p>Thanks in advance for the help! </p>
  
  <p>UPDATE...</p>
  
  <p>Ok so the call back function is being called like so...</p>
  
  <pre><code>loop(10, updateDB);
  </code></pre>
  
  <p>And the callback function passed to loop is as follows...</p>
  
  <pre><code>function updateDB(sql_string, responseObject) {
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host : 'localhost',
        user : 'user',
        password : 'password',
        database : 'database',
    });
    connection.connect();
    var query = sql_string;
    connection.query(query, function(err, results) {
        connection.end();
        if (err) {
          console.log(err);
          responseObject.push({"queryStatus":"FAIL"});
        }
        if (err == null) {
          console.log('Changed ' + results.changedRows + ' rows');
          responseObject.push({"queryStatus":"PASS"});
        }
    });
  };
  </code></pre>