把这个代码,我添加了一个HTTP服务器的典型节点JS例如5秒的延迟,以模拟一些异步工作正在进行别处:为什么setTimeout会阻止我的Node.js应用程序?
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的全部重点是能够从单个线程运行异步启动?
仅供参考,您还需要注意浏览器喜欢制作的favicon请求以及页面请求,这也会使问题复杂化。 – jfriend00