Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send response asynchronously in nodejs / express

     const express = require("express");
     const router = express.Router();

     router.get("/", async (req, res, next) => {
         setTimeout(() => {
             res.send("Hello Stackoverflow");
         }, 10000);
     });

     module.exports = router;

When i send a get request from two browser tabs at same time first request gets completed in 10 seconds and second one takes 20 seconds.

I expected both the requests to get completed in 10 seconds as i used setTimeout to make it async.
Am i doing something wrong here or nodejs does’t take another request before completing the first one ?

What i want this code to do is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

request ──> setTimeout
request ──> setTimeout
setTimeout completes ──> send response
setTimeout completes ──> send response

what it currently doing is :

request ──> setTimeout
setTimeout completes ──> send response
request ──> setTimeout
setTimeout completes ──> send response

How can i achieve this ?

>Solution :

This is caused by your browser wanting to reuse the connection to the Express server for multiple requests because by default, Express (actually, Node.js’s http server does this) is telling it to by setting the header Connection: keep-alive (see below for more information).

To be able to reuse the connection, it’ll have to wait for a request to finish before it can send another request over the same connection.

In your case, the first request takes 10 seconds, and only then is the second request sent.

To illustrate this behaviour, try this:

     router.get("/", async (req, res, next) => {
         res.set('connection', 'close');
         setTimeout(() => {
             res.send("Hello Stackoverflow");
         }, 10000);
     });

This tells the browser that the connection should be closed after each request, which means that it will create a new connection for the second request instead of waiting for the first request to finish.

For more information, look here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading