如何在node.js中asynchronous使用setTimeout
我是新来的node.js,我试图使用setTimeout来模拟长连接,并希望它asynchronous的行为。
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中的所有内容都应该是asynchronous的。 那么,这里有什么问题?
SetTimeout
是asynchronous的,你不需要中间的匿名函数,就写这个。
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秒,这意味着它是asynchronous的。 您可以使用ab工具来检查,或者如果您编程节点,可能更容易安装http-perf 。 并运行nperf -c 10 -n 10 http://127.0.0.1:8124
你需要在新的过程中运行你的睡眠。 有一个模块可以帮助你( https://github.com/cramforce/node-worker ),或者你可以看看有关产卵的正常api文档。
varasynchronous,
__slice = [] .slice;
async = require(“async”);
async.setTimeOut = function(){
var arg,args,callback,delay,runWithTimeOut;
callback = arguments [0],delay = arguments [1],arg = arguments [2],args = 4 <= arguments.length? __slice.call(arguments,3):[];
runWithTimeOut = function(){
return setTimeout(callback,delay,arg,args);
};
返回async.parallel([runWithTimeOut]);
};