我已經看到類似的堆棧溢出問題,但沒有一個完全潛入我的問題?我熟悉事件隊列,他們如何工作以及如何實施。我是node.js的新手,我試圖圍繞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的某處,還是內置於解釋器?還有,主函數是如何相對於主事件循環調用的?
事件隊列是內置的。當事件發生時,它將事件推入調用堆棧,也是內置的。調用堆棧中的調用在當前調用完成之前不會被調用。 – Blindman67