我是新来的node.js,我尝试使用setTimeout来模拟长连接并希望它异步执行。如何在node.js中异步使用setTimeout
var http = require('http');
http.createServer(function (request, response) {
console.log('New request @ ' + request.url);
(function (response) {
setTimeout(function() {
console.log('Time is up');
response.writeHead(200, {"Content-Type": "text/plain"});
response.end('Hello World\n');
}, 3000);
})(response);
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
但是,上面的代码表现得像一个同步单线程应用程序,它每3秒只能处理一个请求。
我认为node.js中的所有内容都应该异步执行。那么,这里有什么问题?
我测试过ab,你说的对,setTimeout是一个异步函数。但是,如果我同时在Chrome中打开多个标签,它会在5秒钟间隔内逐一结束,这有点奇怪。 – Jack
我认为你只是没有足够的快速点击Chrome中的标签.. :) – balazs
Chrome不会同时请求相同的URL。如果您为该网址添加了一个变体,例如第一个选项卡请求http://127.0.0.1:8124/0,第二个请求请求http://127.0.0.1:8124/1等,那么他们应该像你期望的那样行事。请参阅http://stackoverflow.com/questions/15852011/why-settimeout-blocks-eventloop – Jason