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.
Pseudo:
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;
}
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.
Edit:
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 > 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 ());
}
getFromDB(with the SQL omitted is fine)?Requests can only be made in the LoggedIn state, not the SentClientRequest statenew Req()call respond to the current message with the data or an error. Then if there's still requests inside your request queue, have it do the same. So all the requests arriving through the socket can stay synchronous. Only the database query triggering the socket to send the response is async, since you want to wait for the prev query to finish instead of running all queries in parallel. Storing pending queries can just be as simple as pushing and popping an array.