Javascript 关于 app.listen() 回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33222074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
About app.listen() callback
提问by Okem
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:
我是 javascript 新手,现在我正在学习 express.js,但是我得到了一些让我对它们的工作方式感到困惑的代码。我试图弄清楚这段代码是如何工作的,但我仍然不明白:
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()
.
我的问题是,当服务器变量从app.listen()
.
回答by DontVoteMeDown
The anonymous function is in fact a callbackwhich is called after the app initialization. Check this doc(app.listen()
is the same as server.listen()
):
匿名函数实际上是在应用程序初始化后调用的回调。检查此文档(app.listen()
与相同server.listen()
):
This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event.
这个函数是异步的。最后一个参数回调将被添加为 'listening' 事件的监听器。
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.
所以该方法app.listen()
返回一个对象,var server
但它还没有调用回调。这就是server
变量在回调中可用的原因,它是在调用回调函数之前创建的。
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...
调用 app.listen()。
app.listen() 执行。
调用 app.listen 的回调函数。
示例应用程序在...