title: How to use recursion in node.js mysql without breaking connection?
body: <p>I am using iojs and node-mysql. This is my first foray into async server-side programming. It is essentially a batch job: run it all once, exit. I am specifically trying to do this on a table full of revisions:</p>
  
  <p><em>For each document edited in the past year; for each revision to that document made in the past year; get the prior revision and diff its content with the current revision.</em></p>
  
  <p>So, I am using the results of one query (<em>for each document</em>) to fire off an arbitrary number of additional queries (<em>for each revision</em>) that must themselves recurse (<em>get the prior revision</em>). </p>
  
  <p>I can't figure out how to close the database connection. Near as I can tell, the recursion is the confounding factor: If I remove that from the code, then I can close the db connection. But I need to recurse.</p>
  
  <p>Here is a minimal example (assume requires and config are OK) that accomplishes the behavior I'm seeing in my program.</p>
  
  <pre><code>var con = mysql.createConnection(db_config);
  con.connect();
  
  con.query('SELECT field_2 FROM test_table', function(err, rows) {
      if (err) throw err;
      rows.forEach(function(row) {
          second_query(row.field_2);
      });
  
      // using this here works if there is no recursion, even if second_query runs long
      // using this here does not work if there is recursion
      // removing this allows the program to run to completion, but the event loop never exits
      con.end()
  });
  
  function second_query(key) {
      con.query('SELECT * FROM test_table_2 WHERE field_2 &gt; ?', [key], function(err, rows) {
          if (err) throw err;
          if (rows.length &gt; 0) {
              rows.forEach(function(row) {
                  console.log(row.field_2);
              });
              second_query(key + 1);
          }
      });
  }
  </code></pre>
  
  <p>I have tried very hard to solve the problem by registering database queries in an accumulator and decrementing the accumulator as each query ends, but that hasn't produced predictable success yet and it makes the code painful to work with.</p>