About app.listen() callback

前端 未结 1 1380
走了就别回头了
走了就别回头了 2021-02-02 11:45

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

相关标签:
1条回答
  • 2021-02-02 12:24

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

    0 讨论(0)
提交回复
热议问题