title: Making multiple mysql calls using JS promise in Node.js
body: <p><strong>GOAL:</strong></p>
  
  <p>I am trying to make multiple SQL queries using the "mysql" module in Node.js such that the result of one query is used as input in the next statement. </p>
  
  <pre><code>sql1 = SELECT id FROM users WHERE email=? // get user id from email
  val1 = test@email.com
  
  sql2 = SELECT something FROM profiles WHERE user_id=?
  val2 = user_id // result of sql1
  </code></pre>
  
  <p><strong>APPROACH:</strong></p>
  
  <p>I am using a JS "promise" to achieve this:</p>
  
  <pre><code>var run_query = function(conn,sql){
  
  return new Promise(function (fulfill, reject){
  
      conn.query(sql, val, function(err, res) {
  
          if(err) reject(err);
          else    fulfill(res);
  
      });
  
  });
  
  }
  
  var conn = db.config(mysql);
  
  run_query(conn,[ 'SELECT id FROM users WHERE email=?' , ['test@email.com'] ]).then(function(result){
  
    console.log(result.id); // result of 1st query
  
    return run_query(conn,[ 'SELECT something FROM profiles WHERE user_id=?' , [result.id] ]);
  
  }).then(function(result){
  
      console.log(result.something); // result of 2nd query 
  
  }).catch(function(err){
  
      console.log('there was an error', err);
  
  });
  
  conn.end();
  </code></pre>
  
  <p><strong>ISSUE:</strong></p>
  
  <p>The 1st query returns the correct result, but the second query throws the following error from the mysql module:</p>
  
  <pre><code>Error: Cannot enqueue Query after invoking quit.
  ~blah blah blah~
  code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false 
  </code></pre>
  
  <p><strong>MY ATTEMPTS TO RESOLVE:</strong></p>
  
  <p>I believe this has something to do with multiple calls being made while the connection is open and <strong>conn.end();</strong> being called at the very end. I moved it around a bit but that didnt work.</p>
  
  <p>I tried turning on multiple statement for the mysql module</p>
  
  <pre><code>var conn = mysql.createConnection({multipleStatements: true}); 
  </code></pre>
  
  <p>..but that didnt work either.</p>
  
  <p>How does one use the mysql node module with a JS promise structure?</p>