本文介绍了关于app.listen()回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,现在我学习了express.js,但是我得到了一些代码,使我对其工作方式感到困惑.我正试图弄清楚这段代码是如何工作的,但仍然不明白:

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);
});

我的问题是,当服务器变量从app.listen()获取返回值时,该匿名函数如何使用服务器变量.

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

推荐答案

匿名函数实际上是回调,在应用初始化后会被调用.检查此文档(app.listen()server.listen()相同):

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()):

因此方法app.listen()将对象返回到var server,但尚未调用回调.这就是server变量在回调内部可用的原因,它是在调用回调函数之前创建的.

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:

app.listen()已执行.

app.listen() executed.

调用app.listen的回调函数.

Calling app.listen's callback function.

示例应用程序正在监听...

Example app listening at...

这篇关于关于app.listen()回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 14:23