【发布时间】:2015-11-04 00:53:15
【问题描述】:
我在堆栈溢出方面看到过类似的问题,但没有一个完全深入到我的问题中?我熟悉事件队列,它们如何工作以及实现它们。我是 node.js 的新手,我正试图了解 Node.js 是如何做到的。
在 c++ 应用程序中,您可以执行以下操作:
int main(){
std::vector<Handler*> handlers;
BlockingQueue queue = new BlockingQueue();
//Add all the handlers call constructors and other such initialization
//Then run the event loop
while(true){
Event e = queue.pop();
for( std::vector<Handler>::iterator it = handlers.begin(); it != handlers.end(); ++it){
*it.handle(e);
}
}
}
现在对于 node.js,我可能有一个名为 main.js 的主文件,看起来像。
var http = require("http");
function main(){
// Console will print the message
console.log('Server running at http://127.0.0.1:8080/');
var server = http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
});
server.listen(8080);
console.log('Main completed');
}
main();
我了解 server.listen 正在将处理程序附加到事件队列,并且我们正在添加类似于 c++ 示例的回调。
我的问题是。事件队列在哪里?它是在某个地方的javascript中还是内置在解释器中?另外,相对于主事件循环,主函数是如何被调用的?
【问题讨论】:
-
事件队列是内置的。它在事件发生时将事件推送到同样内置的调用堆栈上。在当前调用完成之前,不会调用调用堆栈上的调用。
标签: javascript c++ node.js