title: Queueing SQL queries
body: <p>I have a socket that listens to events (strings) through UDP. Each time it gets a string an SQL request is generated. My problem is making it run asynchronously, so that requests queue up and not try to access the database while another query is running.</p>
  
  <p>Pseudo:</p>
  
  <pre><code>socket.on('message', function (msg) {
      switch (msg) {
          case "case1":
              storeRows();
              break;
      //there's a new message every 1-2 secs
      ...
  }
  var rows = []; //push results of all queries here
  function storeRows() {
      rows.push(getFromDB());
  }
  
  function getFromDB() {
      var sqlString = "SELECT * ..."
      var req = new Req(sqlString, function(err, rowCount) {
  ...
      }
  var resultsArray = [];
  req.on('row', function (cols) {
      //add results to resultsArray
  }
  return resultsArray;
  }
  </code></pre>
  
  <p>Basically I need getFromDB() to run asynchronously, wait for the previous query to finish before running the next one. This I don't know how to do. I'm using tedious.js to access SQL Server DB.</p>
  
  <p>Edit:</p>
  
  <pre><code>var config = {
      userName: "admin",
      password: "pw",
      server: "test",
      domain: "test",
      options: {
          port: '10322'
      }
  }
  connection = new Connection(config);
  connection.on('connect') {
      isConnected = true;
  }
  
  getCoordinates(vehicleID, fromTime, toTime) { 
      var SQLString = "Select * FROM coordinates WHERE TimeStamp BETWEEN '" + fromTime + "' AND '" + toTime + "' AND vehicleID = " + vehicleID;
      var rowsToSend = [];
      var req = new Req(SQLString, function(err, rowCount) {
          if (err) console.log(err)
          else console.log(rowCount);
      }
  
      req.on('row', function (columns) {
          var rowArray = [];
          columns.forEach(function (column) {
              var colValue = column.value;
              switch (column.metadata.colName) {
                  case "ID":
                      if (rowArray.length &gt; 0)                   
                          rowsToSend.push(rowArray);
                          rowArray = new Array();
                          break;
  
                  default:                     
                      rowArray.push(colValue);
                      break;
                  }
           });
           rowsToSend.push(rowArray);
      });
      connection.execSql(req);
  
      req.on('doneProc', function () {
          return(rowsToSend);
      }  
  }
  
  //called every few seconds
  function runQueries() {
      someArray.push(getCoordinates ());
  }
  </code></pre>