我正在努力学习一些关于 node.js 的知识,并且我已经达到了一个障碍点(没有双关语的意思)。我意识到以前曾以各种方式提出过这个问题,但我觉得我已经消化了这些答案,但仍然遗漏了一些东西。
下面的代码也在要点上:https ://gist.github.com/3866651
基本上,我不相信 setTimeout 调用会阻塞,因为“setTimeout called”行会立即打印出来。但是,我很难理解为什么它仍然需要整整 20 秒来处理两个连续发出的请求。
我真的错过了什么吗?有没有办法在第一个 sendTimeout 发送响应之前获得第二个请求的服务?
我看过“子进程”,但这似乎与系统调用直接相关,而不是调用 javascript 函数。
var http = require("http");
function do_thing(response, callback){
var d=new Date();
console.log('calling setTimeout '+d.toLocaleTimeString());
var timer = setTimeout(function(){
var d=new Date();
console.log('timeout callback '+d.toLocaleTimeString());
respond(response);
}, 10000);
var d2=new Date();
console.log('setTimeout called '+d2.toLocaleTimeString());
}
function respond(response){
var d=new Date();
console.log('sending response '+d.toLocaleTimeString());
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("hello at "+d.toLocaleTimeString());
response.end();
}
http.createServer(function(request, response) {
var d=new Date();
console.log('got request '+d.toLocaleTimeString());
do_thing(response, respond);
}).listen(8888);
var d=new Date();
console.log('running... '+d.toLocaleTimeString());
//Two web requests in close succession, still have to wait 20 secs for 2nd request to complete...
//OUTPUT AS FOLLOWS:
//
//running... 12:12:00
//got request 12:12:06
//calling setTimeout 12:12:06
//setTimeout called 12:12:06
//timeout callback 12:12:16
//sending response 12:12:16
//got request 12:12:16
//calling setTimeout 12:12:16
//setTimeout called 12:12:16
//timeout callback 12:12:26
//sending response 12:12:26