最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - nodejs mssql return recordset - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 5

The 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);
发布评论

评论列表(0)

  1. 暂无评论