title: node.js : For each over rows and update asynchronously?
body: <p>I need to query rows from a database, process some information per row, and then update each row with the result.</p>
  
  <p>This is my example code where the intention is to loop over each row and update the label:</p>
  
  <pre><code>var mysql = require('mysql');
  
  var db = mysql.createConnection(config.database);
  
  db.connect(function() {
      db.query('SELECT id FROM testTable', function (err, rows) {
          if (err) {
              console.log(err);
          } else {
              if (rows.length) {
                  for (var i = 0, len = rows.length; i &lt; len; i++) {
                      var row = rows[i];
                      console.log(row);
  
                      var label = "Label_"+row.id;
  
                      db.query('UPDATE testTable SET label = ? WHERE id = ?', [label, row.id], function(err, result) {
                          if (err) {
                              console.log(err);
                          } else {
                              console.log("Set label on row %s", row.id);
                          }
                      })
                  }
              }
          }
      })
  });
  </code></pre>
  
  <p>The output of this is:</p>
  
  <pre><code>{ id: 1 }
  { id: 2 }
  { id: 3 }
  { id: 4 }
  Set label on row 4
  Set label on row 4
  Set label on row 4
  Set label on row 4
  </code></pre>
  
  <p>So, as you can see, I've updated row 4 four times instead of four rows once each.  Whilst I new the queries would be non-blocking, I thought the values would change for each one.</p>
  
  <p>I know I can change my code to use <code>rows.forEach(function(){...})</code> and that then executes each UPDATE one after the other and that would be ok.  But to help my understanding I would like to know how I can correctly execute the updates asynchronously.</p>