javascript nodejs mssql 返回记录集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31124671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs mssql return recordset
提问by JiJiJiAR
Im trying to past the recordset from mssql request.query like a return value. Following the code on https://www.npmjs.com/package/mssqlis easy to make a a console output but when I try to asign the recordset to another variable doesnt work. What Im doing wrong?
我试图从 mssql request.query 像返回值一样传递记录集。按照https://www.npmjs.com/package/mssql上的代码很容易制作控制台输出,但是当我尝试将记录集分配给另一个变量时不起作用。我做错了什么?
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.
谢谢。
回答by Explosion Pills
The query is run asynchronously. console.log
actually runs before resultado = recordset[0].VehiCLASS
completes, so it's not set.
查询是异步运行的。 console.log
实际上在resultado = recordset[0].VehiCLASS
完成之前运行,所以它没有设置。
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);