2012-12-20 44 views
5

我是新来的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中的所有内容都应该异步执行。那么,这里有什么问题?

回答

8

SetTimeout是异步的,你不需要中间的匿名函数,只需写这个。

var http = require('http'); 

http.createServer(function (request, response) { 
    console.log('New request @ ' + request.url); 
    setTimeout(function() { 
    console.log('Time is up'); 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.end('Hello World\n'); 
    }, 3000); 
}).listen(8124); 

console.log('Server running at http://127.0.0.1:8124/'); 

如果您生成10个并发请求,则总计时间约为3秒,这意味着它是异步的。您可以使用ab工具来检查,或者如果您编程节点,可能更容易安装http-perf。并运行nperf -c 10 -n 10 http://127.0.0.1:8124

+0

我测试过ab,你说的对,setTimeout是一个异步函数。但是,如果我同时在Chrome中打开多个标签,它会在5秒钟间隔内逐一结束,这有点奇怪。 – Jack

+0

我认为你只是没有足够的快速点击Chrome中的标签.. :) – balazs

+2

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

-3

var async,
__slice = [] .slice;

async = require(“async”);

async.setTimeOut =函数(){
       变种精氨酸,指定参数时,回调,延迟,runWithTimeOut; callback = arguments [0],delay = arguments [1],arg = arguments [2],args = 4 < = arguments.length?
          __slice.call(arguments,3):[];
        runWithTimeOut =函数(){
               返回的setTimeout(回调,延迟,精氨酸,参数);
       };

       返回async.parallel([runWithTimeOut]);
};