Javascript 为什么setTimeout会阻止我的Node.js应用程序?

Javascript 为什么setTimeout会阻止我的Node.js应用程序?,javascript,node.js,asynchronous,Javascript,Node.js,Asynchronous,以这段代码为例,这是Http服务器的典型node js示例,我在其中添加了5秒的延迟,以模拟在其他地方进行的一些异步工作: const http = require('http'); const hostname = '127.0.0.1'; const port = 8080; http.createServer((req, res) => { setTimeout(()=>{ res.writeHead(200, { 'Content-Type': 'text

以这段代码为例,这是Http服务器的典型node js示例,我在其中添加了5秒的延迟,以模拟在其他地方进行的一些异步工作:

const http = require('http');

const hostname = '127.0.0.1';
const port = 8080;

http.createServer((req, res) => {
  setTimeout(()=>{
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello World\n');
  },5000);
}).listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
我所期望的是,当我打开5个选项卡时,比如说在打开每个选项卡之间有半秒的延迟,服务器应该或多或少地按照以下时间“响应”每个选项卡:

t=0s - I open first tab
t=0.5s - I open second tab
t=1s - I open third tab
...
t=5s - First tab stops loading, server has replied
t=5.5s - Second tab stops loading, server has replied
t=6s - Third tab stops loading, server has replied
t=6.5s - Fourth tab stops loading, server has replied
t=7s - Fifth tab stops loading, server has replied
然而,我看到的行为如下:

t=0s - I open first tab
t=0.5s - I open second tab
t=1s - I open third tab
...
t=5s - First tab stops loading, server has replied
t=10s - Second tab stops loading, server has replied
t=15s - Third tab stops loading, server has replied
t=20s - Fourth tab stops loading, server has replied
t=25s - Fifth tab stops loading, server has replied

就好像直到第一个请求完成后才开始运行后续请求一样。我是不是遗漏了什么?我认为Node JS的全部意义在于能够从单个线程运行异步TAK?

问题不在于代码或Node.JS,而在于如何设置测试

您错误地认为您的浏览器将发出5个并发请求,但事实并非如此。不同的浏览器具有不同的行为,但通常浏览器将同时连接到单个源的最大数量限制为非常低的数量。HTTP规范给出了建议的最大值。事实上,我很惊讶地看到Chrome只打开了1个到localhost的连接,因为我知道Chrome打开了6个到其他来源的连接——刚刚学到了一些新东西

使用不同的工具运行您的测试,您可以控制并确保它正在进行并发请求。然后您将看到预期的行为

例如,我运行了您的代码,并使用Apache基准测试,如下所示。参数表明:
-n10
是发出10个请求,
-c10
是使用并发10(即,同时发出所有10个请求)。正如您在下面的结果中所看到的,所有请求的总时间约为5秒(“每个请求的时间”为0.5秒):

~$ab-n10-c10http://127.0.0.1:8080/
这是ApacheBench,版本2.3
版权1996亚当·特维斯,宙斯科技有限公司,http://www.zeustech.net/
授权给Apache软件基金会,http://www.apache.org/
基准测试127.0.0.1(耐心)…完成
服务器软件:
服务器主机名:127.0.0.1
服务器端口:8080
文档路径:/
文件长度:12字节
并发级别:10
测试时间:5.019秒
完成申请:10
失败的请求:0
传输总量:1130字节
传输的HTML:120字节
每秒请求数:1.99[#秒](平均值)
每次请求的时间:5019.151[ms](平均值)
每个请求的时间:501.915[ms](所有并发请求的平均时间)
传输速率:接收到0.22[千字节/秒]
连接时间(毫秒)
最小平均值[+/-sd]最大中值
连接:0.1 0 0
处理:5017 5018 0.3 5018 5018
轮候人数:500850080.250085009
总计:5018 5018 0.2 5019 5019
误差:总时间的中位数和平均值是标准值的两倍以上
分离。这些结果并不可靠。
在特定时间内服务的请求百分比(毫秒)
50%   5019
66%   5019
75%   5019
80%   5019
90%   5019
95%   5019
98%   5019
99%   5019
100%5019(最长请求)

似乎这只发生在某些浏览器中,我尝试了safari,它的工作原理与预期相符。
所以我猜Chrome会限制同一时间对同一资源的相同请求的数量

OP还可以查看Chrome调试器的网络选项卡,查看请求何时实际发送到服务器。调试器“网络”选项卡中的时间线将讲述整个过程。先生,你说得很对,你尝试过让chrome、firefox和edge并排出现,并在每个浏览器上刷新页面,我得到了预期的结果!!也感谢您花时间测试它并发布结果!王牌回答,这就是为什么我活得如此:)@jfriend00是的,我甚至没有想到我会成为一个浏览器问题@RubenSerrate-是的,浏览器试图保护网页同时加载到任何给定主机上的负载。我不确定那里的整个历史,但每个浏览器都有用于此目的的连接限制编码,如果你不知道这是怎么回事,它确实会混淆你自己的测试。只有一个并发连接,因为所有连接都指向同一个URL,而不是因为它在本地主机上。Firefox也在这样做(阻止与同一主机的连接数)仅供参考,您还必须注意浏览器喜欢发出的favicon请求以及可能使问题复杂化的页面请求。
~ $ ab -n 10 -c 10 http://127.0.0.1:8080/
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient).....done


Server Software:
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /
Document Length:        12 bytes

Concurrency Level:      10
Time taken for tests:   5.019 seconds
Complete requests:      10
Failed requests:        0
Total transferred:      1130 bytes
HTML transferred:       120 bytes
Requests per second:    1.99 [#/sec] (mean)
Time per request:       5019.151 [ms] (mean)
Time per request:       501.915 [ms] (mean, across all concurrent requests)
Transfer rate:          0.22 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       0
Processing:  5017 5018   0.3   5018    5018
Waiting:     5008 5008   0.2   5008    5009
Total:       5018 5018   0.2   5019    5019
ERROR: The median and mean for the total time are more than twice the standard
       deviation apart. These results are NOT reliable.

Percentage of the requests served within a certain time (ms)
  50%   5019
  66%   5019
  75%   5019
  80%   5019
  90%   5019
  95%   5019
  98%   5019
  99%   5019
 100%   5019 (longest request)