Sql server NodeJS&;SQL Server(回调)
在创建回调时遇到麻烦 例如:Sql server NodeJS&;SQL Server(回调),sql-server,node.js,Sql Server,Node.js,在创建回调时遇到麻烦 例如: var connection = new sql.Connection(config); connection.connect().then(function() { var request = new sql.Request(connection); // or: var request = connection.request(); request.query('SELECT TOP 1 EQUIPMENT_ID FROM T_EQUIPMEN
var connection = new sql.Connection(config);
connection.connect().then(function() {
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('SELECT TOP 1 EQUIPMENT_ID FROM T_EQUIPMENT', function(err, recordset) {
console.dir(recordset);
});
}).catch(function(err) {
// ...
});
使用npm mssql:
在继续下一个任务之前,我需要确保我拥有这些数据
因此,让我们说,在这之后,我有一些类似:
console.log("completed");
因为它是异步的,“completed”将首先出现,然后是查询
如何正确地创建回调,以便在回调完成后处理下一个任务,而不必在请求中“嵌套”
如果不可能,请告诉我,我只想确保我在做最佳实践
多谢各位 略加修改:request.query('SELECT TOP 1 device_ID FROM T_device',function(err,recordset){//console.dir();fn(recordset);connection.close();});非常感谢。
// This is the function you call to connect to SQL.
// You will call this function and pass it a function you want executed
// after this function is completed which is where you see fn() at the bottom
function connectToSQL(fn) {
connection.connect().then(function() {
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('SELECT TOP 1 EQUIPMENT_ID FROM T_EQUIPMENT', function(err, recordset) {
console.dir(recordset);
});
fn();
}).catch(function(err) {
// ...
});
// Calling the function using a callback
// The function you are sending the function is the logic that will be executed
// when the fn() is called in the connectToSQL function
connectToSQL(function() {
console.log("completed");
});