title: How can I execute a query based on the result of another query? (Express, NodeJS, mysql)
body: <p>I am trying to generate a session ID when an API call is made to my 'generateSession' endpoint. I want to make sure that I don't have any duplicate session ID, so I query the database checking for a match on the generated ID. If there isn't a match, the ID is valid and I make a second query to add an active user with said session ID. </p>
  
  <p>Although my first query executes, the 'id_is_valid' boolean never gets set to true so my program gets stuck in the while loop.</p>
  
  <p>I am fairly new to JavaScript, but from some research, I'm pretty sure the problem is due to the asynchronous nature of the database call. However, I'm not sure where to go from there. Could anyone with more js knowledge offer me some direction?</p>
  
  <p>Thanks!</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  
  var myDB = require('../db-connection');
  
  function generateSession() {
      var session_id = '';
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  
      for (var i = 0; i &lt; 30; i++) session_id += possible.charAt(Math.floor(Math.random() * possible.length));
  
      return session_id;
  }
  
  router.get('/generateSession', function(req, res){
      var session_id = '';
      var id_is_valid = false;
      while (!id_is_valid){
          session_id = generateSession();
  
          myDB.query("SELECT * FROM activeUser WHERE session_id = ?", [session_id], function(error, results, field){
              if(error) throw error;
              else{
                  if (results.length === 0) is_is_valid = true;
              }
          });
      }
  
      myDB.query("INSERT INTO activeUser (is_registered, session_id) VALUES (0, ?)", [session_id], function(error, results, fields){
          if (error) res.send('{"success": false}');
          else res.send('{"success": true, "session_id": "' + session_id + '"}');
      });
  });
  </code></pre>