Im trying to past the recordset from mssql request.query like a return value. Following the code on is easy to make a a console output but when I try to asign the recordset to another variable doesnt work. What Im doing wrong?
var sql = require('mssql');
var config = {
user: 'sa',
password: 'XXXXXX',
server: '192.168.8.25',
database: '3TWIMDB',
}
var resultado='';
sql.connect(config, function(err){
var request = new sql.Request();
request.query('select 1 as VehiCLASS',function(err,recordset){
console.log(recordset[0].VehiCLASS);
resultado = recordset[0].VehiCLASS;
});
sql.close();
});
console.log("rsul: "+resultado);
Im trying to past the recordset from mssql request.query like a return value. Following the code on https://www.npmjs./package/mssql is easy to make a a console output but when I try to asign the recordset to another variable doesnt work. What Im doing wrong?
var sql = require('mssql');
var config = {
user: 'sa',
password: 'XXXXXX',
server: '192.168.8.25',
database: '3TWIMDB',
}
var resultado='';
sql.connect(config, function(err){
var request = new sql.Request();
request.query('select 1 as VehiCLASS',function(err,recordset){
console.log(recordset[0].VehiCLASS);
resultado = recordset[0].VehiCLASS;
});
sql.close();
});
console.log("rsul: "+resultado);
Thanks.
Share Improve this question edited Jul 6, 2015 at 18:01 Joel 16.1k6 gold badges39 silver badges63 bronze badges asked Jun 29, 2015 at 20:09 JiJiJiARJiJiJiAR 211 gold badge1 silver badge3 bronze badges1 Answer
Reset to default 5The query is run asynchronously. console.log
actually runs before resultado = recordset[0].VehiCLASS
pletes, so it's not set.
You must synchronize any code that relies on asynchronous operations. You have to do this by using the callbacks:
resultado = recordset[0].VehiCLASS;
console.log("rsul: ", resultado);
You may also specify your own callback function to prevent nesting:
function queryComplete(err, result) {
// should handle error
console.log("rsul: ", result);
}
resultado = recordset[0].VehiCLASS;
queryComplete(null, resultado);