NodeJS& SQL Server(回调)

时间:2015-04-06 18:06:19

标签: 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_EQUIPMENT', function(err, recordset) {
        console.dir(recordset);
    });

}).catch(function(err) {
    // ...
});

使用npm mssql:

我需要确保在继续下一个任务之前获得这些数据。

所以,在此之后我会说:

console.log("completed");

因为它是异步的,所以"完成"先来,然后是查询。

如何正确创建一个回调,以便在完成后再处理下一个任务,而不必'#34; nest"在请求中。

如果不可能让我知道,我只是想确保我做的是最好的做法。

非常感谢!

1 个答案:

答案 0 :(得分:2)

// 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");
});