0

Having troubling creating a callback.

Example:

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

Using npm mssql:

I need to make sure I have this data prior to continuing my next task.

So lets say after this I have something like:

console.log("completed");

Because it is async, the "completed" will come first, then the query.

How do properly create a callback so that when it is completed then process the next task without having to "nest" within the request.

If it's not possible let me know, I just want to make sure I am doing best practices.

Thank you very much!

1 Answer 1

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");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Slightly modified it.: request.query('SELECT TOP 1 EQUIPMENT_ID FROM T_EQUIPMENT', function (err, recordset) { //console.dir(); fn(recordset); connection.close(); }); THANK YOU!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.