简体   繁体   中英

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:

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?

EDIT =>
I suspect this is some chrome only behaviour as the code works in firefox. Also if i open one normal tab and another incognito tab it works as expected.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM