1

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);

2 Answers 2

2

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
})
Sign up to request clarification or add additional context in comments.

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.