简体   繁体   中英

nodejs mssql return recordset

Im trying to past the recordset from mssql request.query like a return value. Following the code on https://www.npmjs.com/package/mssql is easy to make aa 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.

The query is run asynchronously. console.log actually runs before resultado = recordset[0].VehiCLASS completes, 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM