Recover value using Node.js and mssql

Asked

Viewed 451 times

3

I’m having trouble recovering a value using the mssql library

I tried to put a variable in the global scope and update the value using recordset, put everything inside a function passing the value of recordset as return and use setImmediate and setTimeout functions, but still trying to display the date value in the console, it is returned "Undefined"

var express = require('express');
var sql = require("mssql");
var app = express();
var data;

getData();

function getData() {
    var config = {
        user: '', //usuário
        password: '', //senha
        server: '', //servidor
        database: '' //db
    };
    sql.connect(config, function (err) {
        if (err) console.log(err);
        var request = new sql.Request();
        request.query('SELECT ..........', function (err, array) {
            if (err) console.log(err)
            data = array.recordset;
            sql.close();
        });
    });
}

var server = app.listen(8080, function () {
    console.log('Server is running..\n' + data);
});

1 answer

5


request.query is asynchronous. You have to use data only after the query runs. That is, within of callback.

So if you want to start the server only after the query has a result, you have to do so:

         // ...
        request.query('SELECT ..........', function (err, array) {
            if (err) console.log(err)
            // send records as a response
            // console.log(array.recordset);
            data = array.recordset;
            sql.close();
            var server = app.listen(8080, function () {
                console.log('Server is running..\n' + data);
            });
        });
    });
}

Take a look in this other question/answer about ideas for chaining asynchronous code.

  • And how could I use the value returned by "date" outside this function? The intention, in the end, is to take the resulting value of the query and use this module in another file through module.Xports

  • @leocabrallce the trick and difference in the way of thinking in asynchronous code is that everything is chained. Other parts of the code cannot run before this one if you need to data. So I gave the link to the other question/answer. If you have a specific problem, ask a question that we will help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.