I've just started learning node.js and express and there's something that confuses me a bit in the "hello world" example on the express.js website. In the example, they refer to the server variable inside the callback function.
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
Does app.listen()
return a value to server variable before it executes the callback function? How can it do that and how does it work? Is this the same for all callback functions in node (and javascript)?
I would just like a simple explanation of the execution process.
To be clear, I understand that the callback function has access to the server variable. But if the app.listen method executes the callback function before it returns a value to the server variable, wouldn't that mean that the server variable is still underfined when you try to access server.adress()? That is what I don't understand.
Does app.listen() return a value to server variable before it executes the callback function?
Yes, exactly. app.listen()
resembles to the plain Node.js server.listen
method.
The callback is an shortcut for assigning the server an listener to the listening
event.
You could do the same with the following code:
var server = app.listen( 3000 );
server.on( "listening", function () {
console.log( "server is listening in port 3000" );
});
How can it do that and how does it work? Is this the same for all callback functions in node (and javascript)?
This happens because IO events in Node.js are all run asynchronously (with exceptions from the fs
module) - this is, they will only take place when other synchronous code have finished to run.
This works the same in browser JS - if you run some JS process synchronously, any events triggered (like click
, blur
, etc) will only execute after that one finishes.
A function has access to all the variables that existed in the scope where it was created (unless it masks them).
var in_the_global_scope = 1;
function outer() {
function inner() {
alert(in_the_global_scope);
}
inner();
}
inner
has access to any variable declared in inner
, outer
and the global scope.
A function being a callback isn't really relevant.
The listen
method itself doesn't have access to server
because listen
was created in a different scope.
But if it returns a value, how can it then execute the callback function?
Because it doesn't just execute the callback. It waits for an event and the callback gets fired in reaction to that.
var timeOutId = setTimeout(function() {
alert(timeOutId);
}, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With