请看这段代码,典型的Node.js Http服务器示例。我在其中添加了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 的整个意义在于能够从单线程运行异步任务,您觉得呢?