Retrieve value using node.js and mssql

2

I'm having trouble retrieving a value using the mssql library

I have tried to put a variable in global scope and update the value using the recordset, put everything inside a function passing the value of the recordset as a return and use functions of setImmediate and setTimeout, but still trying to display the value in the console of date, 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);
});
    
asked by anonymous 24.08.2017 / 12:04

1 answer

4

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

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

         // ...
        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 at this other question / answer about ideas for chaining asynchronous code.

    
24.08.2017 / 12:07