0
votes

i am having trouble to get a callback function "fn()" to work on the connection part in code below. The Error handling works fine for the Query e.g. if I specify an invalid SQL string, but if the connection fails, the .catch(function (fn,err) line does not work. I am trying to have the callback:

getEmp(function(result, err) {
  if (err) return console.log('Error X: ' + ' - ' + err);
  console.log("completed: " + result.recordset[0].Operation + ' - ' + result.recordset[0].Location);
}, 'Weeke');   

return records as well as query and database connection errors. It returns records and query errors, but does not work for Connection errors. I am brand new to Node and the callbacks are a bit confusing to me. Any help is greatly appreciated. Thanks Alex

var sql = require("mssql");
var config = {
  server: "192.168.1.153\\sqlexpress",
  database: "testdb",
  user: "testdb",
  password: "markus",
  port: "1433"
};

function getEmp(fn, tblname) {
  var conn = new sql.ConnectionPool(config);
  conn.connect().then(function() {
      var req = new sql.Request(conn);
      req.query("SELECT * FROM " + tblname).then(function(result, err) {
          console.log('Var: ' + tblname);
          conn.close();
          fn(result, err);
        })
        .catch(function(err) {
          console.log("Query Error: " + err);
          conn.close();
          fn(null, err);
        });
    })
    .catch(function(fn, err) {
      console.log("Connection Error: " + err);
      fn(null, err);
    });
}

getEmp(function(result, err) {
  if (err) return console.log('Error X: ' + ' - ' + err);
  console.log("completed: " + result.recordset[0].Operation + ' - ' + result.recordset[0].Location);
}, 'Weeke');
1

1 Answers

0
votes

You should always listen for errors on the connection, Whenever something happens with the connection (Connection Error) it emits an error.

So You should be adding a listener to conn.
Something like

function getEmp(fn, tblname) {
  var conn = new sql.ConnectionPool(config);
  conn.connect()
  .then(function() {
    var req = new sql.Request(conn);
    req.query("SELECT * FROM " + tblname).then(function(result, err) {
      console.log('Var: ' + tblname);
      conn.close();
      fn(result, err);
    })
    .catch(function(err) {
      console.log("Query Error: " + err);
      conn.close();
      fn(null, err);
    });
  })
  .catch(function(fn, err) {
    console.log("Connection Error: " + err);
    fn(null, err);
  });
  conn.on('error', err => {
  // ... error handler
  });
}

More on the docs here