0

In some modules I saw this strange way of initializing variable used in a callback.
This particular example is from mssql module:

var sql = require('mssql'); 
var connection = new sql.Connection(config, function (err) {

    var request = new sql.Request(connection);
    request.query('select 1 as number', function (err, recordset) {
        // do something
    });
});

What appears strange to me is that connection is used inside callback as if it is already initialized, and in fact it is.
However I would thought that callback should be run before function sql.Connection() does return. In fact there is no way to run anything after it returns.

So how does this thing work?

1 Answer 1

4

The callback is asynchronous, meaning it doesn't run immediately. Because of this, it gets placed in a queue and run whenever the interpreter isn't doing anything. For example, try this:

var connection = new sql.Connection(config, function(err) {
    console.log('I run second');
});
console.log('I run first');
Sign up to request clarification or add additional context in comments.

2 Comments

So they are betting on pure luck that the interpreter will be busy enough? You can try this in node's REPL to see that sometimes it's not: > var c = (function(cb) { console.log('in func', c); cb(); return 1; })(function () { console.log('in cb', c); }); in func undefined in cb undefined undefined > c 1
@xaxa No, they know that it's going to go on the async stack because it likely has to make some kind of I/O call. See this post for more details on how events are handled.

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.