英文:
Why are multiple requests to a route executed sequentially in Node.js?
问题
在我的Node.js应用程序中有一条路由,每个请求大约需要10秒才能响应。
当我同时对这个路由发出多个请求时,我注意到每个请求都是按顺序执行的,第一个请求需要10秒完成,第二个请求需要20秒,第三个请求需要30秒,依此类推。
有趣的是,当我同时请求应用程序中的另一条路由时,它会在没有延迟的情况下进行处理,这让我相信问题是特定于这个路由。
我想知道为什么对这个特定路由的请求会按顺序处理,而不是并发处理。虽然我知道回调函数和异步编程可以帮助我实现并发处理。我已经了解了Node.js的事件循环及其单线程特性,但我不确定它与我的问题有什么关系。
有人能解释为什么我的对这个特定路由的请求会按顺序处理吗?除了我的主要关注点之外,我也很想知道Node.js是否为应用程序中的每个路由创建了单独的事件循环或调用堆栈?
英文:
I have a route in my Node.js application that takes around 10 seconds to respond to each request.
router.get("/", async (req, res, next) => {
console.log("Service health request.", req.ip, new Date());
let response = { success: true, message: "Service is running!!" };
await wait(10000);
return res.json(response);
});
const wait = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
When I make multiple requests to this route concurrently, I notice that each request is executed sequentially, with the first request taking 10 seconds to complete, the second request taking 20 seconds, the third request taking 30 seconds, and so on.
What's interesting is that when I request another route in my application at the same time, it is processed without delay, which leads me to believe that the issue is specific to the route in question.
router.get("/status", async (req, res, next) => {
console.log("Any other route request.");
let response = { success: true, data: {} };
await wait(10000);
return res.json(response);
});
I am wondering why my requests to this particular route are being processed sequentially instead of concurrently. While I am aware that callbacks and async programming can help me achieve concurrent processing. I have read about Node.js's event loop and its single-threaded nature, but I am not sure how it relates to my issue.
Can anyone explain why my requests to this particular route are being processed sequentially? In addition to my primary concern, I am curious whether Node.js creates a separate event loop or call stack for each route in the application?
答案1
得分: 1
我假设你的测试是在浏览器中进行的。如果是这样,行为与Node.js无关。
浏览器会识别到请求的URL相同,然后逐个发送请求,因为服务器可能会响应缓存控制头,允许它将第一个请求的响应作为后续请求的响应重用。
英文:
I assume your tests are being made in a browser. If so, the behaviour has nothing to do with Node.js.
The browser will recognise that the requests are to the same URL and send them one at a time since the server might respond with cache control headers which would allow it to reuse the response for the first request as the response for the subsequent ones.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论