如何在Node.js中异步使用setTimeout

5

我刚开始学习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中所有东西都应该是异步的。那么,这里的问题是什么?

3个回答

8
< p > SetTimeout 是异步的,你不需要在中间使用匿名函数,只需写成这样即可。 < /p >
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工具进行检查,或者如果您编写Node程序,则可能更容易安装http-perf并运行nperf -c 10 -n 10 http://127.0.0.1:8124

我已经使用ab进行了测试,你是正确的,setTimeout是一个异步函数。但是,如果我同时在Chrome中打开几个选项卡,它在5秒间隔内逐个结束,这有点奇怪。 - Jack
我认为你在Chrome浏览器的标签之间点击得不够快... :) - balazs
2
Chrome不会同时请求相同的URL。如果您向URL添加变化,例如第一个标签请求http://127.0.0.1:8124/0,第二个标签请求http://127.0.0.1:8124/1等等,则它们应该像您所期望的那样运行。请参见https://dev59.com/zXDYa4cB1Zd3GeqPCJuF - Jason

0

-3

var async,
__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);
    };

    return async.parallel([runWithTimeOut]);
};


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接