About the callback to app.listen ()

I'm new to javascript, and now I learn about express.js, but I get code that makes me confused about how they work. I tried to understand how this code works, but I still don't understand:

var server = app.listen(3000, function (){ var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); }); 

My question is how this anonymous function can use the server variable when the server variable gets the return value from app.listen() .

+5
source share
1 answer

An anonymous function is actually a callback that is called after application initialization. Check this document ( app.listen() same as server.listen() ) :

This function is asynchronous. The last parameter callback will be added as a listener for the listen event.

Thus, the app.listen() method returns a var server object, but it has not yet called a callback. This is why the server variable is available inside the callback; it is created before the callback function is called.

To make things clearer, try this test:

 console.log("Calling app.listen()."); var server = app.listen(3000, function (){ console.log("Calling app.listen 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 the node console:

Call app.listen ().

Performed

app.listen ().

Calling the callback function app.listen.

An example of listening to an application ...

+9
source

Source: https://habr.com/ru/post/1234050/


All Articles