NodeJS error and MSSQL module

1

Hello, I'm having an error in the MSSQL module of nodejs for connections to SQL Server. The connection is normal, the problem is time to perform the query, the function does not return anything to the callback.

Connection code:

var sql = require('mssql');

var config = {
user: 'user',
    password: 'password',
    server: 'ip',
    database: 'database',
    connectionTimeout: '5000',
    requestTimeout: '5000',
    options: {encrypt: true}
};

var pool = function(){
    var conn =  new sql.Connection(config, function(err){
        var request = new sql.Request(conn);
        //console.dir(request);
        return request;
    });
    return conn;
}

module.exports = function(){
    return pool;
}

DAO:

function CampanhaDAO(connection){
    this._connection = connection;
    //console.log(this._connection)
}

CampanhaDAO.prototype.getCampanhas = function(){
    var sql = "SELECT * FROM notificacao_campanha";

    this._connection.query(sql, function(err, recordset){

        console.log(recordset);
    });
};

module.exports = function(){
    return CampanhaDAO;
};
    
asked by anonymous 03.02.2017 / 13:48

2 answers

0

Change your getCampanhas method to work with promises and add the connect method before running query :

CampanhaDAO.prototype.getCampanhas = function(){
  var sql = "SELECT * FROM notificacao_campanha";
  var conn = this._connection.query(sql);

  new conn.Request().connect(function(err) {
    conn.query(sql).then(function(recordset){
      console.log(recordset);
      conn.close();
    }).catch(function(err) {
      console.error(err);
    });
  })
};
    
03.02.2017 / 17:23
0

Have you tried the recommended method in documentation through async / await?

const executeQuery = async (query) => {
try {
	const pool = await sql.connect(config);
	const result = await pool.request().query(query);

	return result;
} catch (error) {
	console.error(error);
} finally {
	sql.close();
}
};
    
01.03.2018 / 19:28