If you are new to Node.js like I am, using Tedious to access Azure SQL can be challenging at the beginning. My understanding is that Tedious, while being fully asynchronous, doesn’t support nor Promises nor the more modern async/await pattern. Tedious, in fact, uses events to execute asynchronous code and so a bit of work is needed to make it compatible with Promises.

At the end of the day is just a few lines of code, but the process of discovering those two lines can be quite long and sometime frustrating. There is no clear statement anywhere that shows how to properly do that. I think that’s due to the fact that once you get the grasp of Promises it became absolutely obvious….but if you haven’t got to that point, you’re left in the dark.

Well, let’s shed some light then, and fix this hole in the shared knowledge book that is the internet!

Encapsulate usage of Tedious

To avoid writing the same code again and again, you probably want to encapsulate the business logic that executes a SQL command into a function. Something – in theory – like the following

executeSQL = function(query, params) {
  var result = null;

  const conn = new Connection(...);
  conn.on('connect', err => { ... invoke req ... });

  const req = new Request(query, err => { return result });
  req.addParameter(...params...);
  req.on('rows', columns => { ... build result ... });

  conn.connect();  
}

After the connect``() method has been successfully called, the connect event will happen. From there, the created Request can be executed. The request will generate a row event that allows you to get the result coming in from Azure SQL, and process and store it into a variable of your choice.

#azure sql #javascript #node #developers #development #promises #tedious

Promises, Node, Tedious, Azure SQL. Oh My!
5.50 GEEK