I\'m new in javascript and now i\'m learn about express.js, but i get some code that makes me confused about how they work. I was tring to figure out how this code work but i st
The anonymous function is in fact a callback which is called after the app initialization. Check this doc(app.listen() is the same as server.listen()):
This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event.
So the method app.listen()
returns an object to var server
but it doesn't called the callback yet. That is why the server
variable is available inside the callback, it is created before the callback function is called.
To make things more clear, try this test:
console.log("Calling app.listen().");
var server = app.listen(3000, function (){
console.log("Calling app.listen's callback function.");
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
console.log("app.listen() executed.");
You should see these logs in your node's console:
Calling app.listen().
app.listen() executed.
Calling app.listen's callback function.
Example app listening at...