title: Callbacks and Async Execution in Node?
body: <p>I have a function that generates a bunch of data into a DB for testing, then at the end sends a textual response to the browser. I'm new to node and see the response and text is printing before any of the execution has even completed.</p>
  
  <p>I've tried a bunch of different ways to see sequential execution, below is one of the crazy poor ways, but still not working. What can I do to ensure the for-loop data completes, c.end() executes and then DONE is called?
  //Generate the new data to persist into the database
      function data_generation(call_back) {</p>
  
  <pre><code>  //Force generate random entries into the test DB (eventually change to monitor individual key requests)
    for (var i = 0; i &lt; NUM_ENTRIES; i++) {
      c.query("INSERT INTO individual_key_log \
                (reference_key, access_count, last_updated, last_ip) \
                  VALUES ('Johnson" + Math.random()*100 + "', " + (Math.random()*100) +", '"+Date.now()+"', '"+req.connection.remoteAddress+"'\
                );",
              function(err, rows) {
        if (err) {
          throw err;
        }
        else {
          console.log("Counter: " + counter);
          counter++;
        }
      });
      call_back();
    }
  };
  
  function completion_func() {
    console.log("DONE");
    res.send("done");
  };
  
  
  data_generation(completion_func);
  </code></pre>