About app.listen() callback

余生长醉 提交于 2020-05-09 19:08:56

问题


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 still don't get it:

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 using the server variable, when the server variable getting return value from app.listen().


回答1:


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...



来源:https://stackoverflow.com/questions/33222074/about-app-listen-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!