Kevin Liss
Kevin Liss

Reputation: 136

nodejs mssql query in function

I´m trying to get the result of my query which is running in my function.
But my result is undefined. What i´m doing wrong?

function:

function sqllis(sql_q) {
  sql.connect(dbConfig, function (err) {
    if (err) console.log(err);
    var request = new sql.Request();
    request.query(sql_q, function (err, recordset) {
      return recordset.recordsets;
    });
  });
}

My try to get the result:

var result = sqllis("select * from dbo.sys_user ");
console.log(result);

Upvotes: 2

Views: 6641

Answers (2)

Jonathan Hamel
Jonathan Hamel

Reputation: 1393

The sql.query function uses a callback meaning it is asynchronous code. You cannot resolve the result synchronously. I am not sure whether you are using the sql or mssql npm library, but I'd suggest looking if there is a native promise approach or to wrap your code into a promise oriented approach. If you're using the mssql library, when omitting the callback, it returns automatically a promise and you can use it like this.

function sqllis(sql_q) {
    sql.connect(dbConfig, function (err) {
        if (err) console.log(err);
        var request = new sql.Request();
        return request.query(sql_q);
    });
}

and use it asynchronously like this:

sqllis("select * from dbo.sys_user ")
.then(function(results){ console.log(results) })
.catch(function(err){ console.log(err) });

You can also pass a callback function.

function sqllis(sql_q, callback) {
    sql.connect(dbConfig, function (err) {
        if (err) console.log(err);
        var request = new sql.Request();
        request.query(sql_q, callback);
    });
}

and use it like this

sqllis("select * from dbo.sys_user ", function(err, results){
    console.log(err);
    console.log(results); //results.recordsets
})

Upvotes: 3

Suhail Gupta
Suhail Gupta

Reputation: 23276

You will have to use a callback to return results from an async function.

   function sqllis(sql_q, callback) {
        sql.connect(dbConfig, function (err) {
            if (err) console.log(err);
            var request = new sql.Request();
            request.query(sql_q, function (err, recordset) {
                callback(err, recordset); // USING CALLBACK
            });
        });
    }

    var result = sqllis("select * from dbo.sys_user ", (err,res) => {
         console.log(res);
    })

Reference articles you could go through:

Upvotes: 0

Related Questions