How to avoid node-express from being blocked by fetch call

Viewed 300

I have simulated a time consuming asynchronous operation on the node-express route using setInterval. while the setInterval was waiting, node-express didn't respond to another client's request. what can be done to prevent blocking of the route?

This is the simulation I have used:

I opened two clients and tried to send requests from both of the clients at the same time. the test was done on localhost.

I have tested it again and again, and the second client gets the responses from the server only after all ten of the first client request were responded.

Client:

<button onclick='getManyData()'>Get Data </button>
   
    <script>
        function getManyData(){

            for(let i=0; i<10;i++){
                getData()
            }
        }

        function getData(){
           
            fetch('/api/req1')
            .then(res=>res.json())
            .then(data=>{
               
                console.log(data)
            })

        }
    </script>

Server:

const express = require('express');
const app = express();


app.use(express.static('public'))

app.get('/api/req1', (req, res) => {
    setTimeout(()=>{
        res.send({ ok: true })
    },500)
    
})

app.listen(3000, () => { console.log('listen on port 3000') })

This is how it looks on the network: enter image description here

Update:

I have found that this phenomenon happens only on chrome, but not on firefox (in Firefox, all the requests are answered after approximately 500ms). Any suggestions on why this happens?

0 Answers
Related