mat
mat

Reputation: 1

Can not make 2 request parallel - nodejs

I have this code:

import http from 'http';

const longComputation = () => {
  return new Promise((resovle) => {
    console.log('started');
    let sum = 0;
    for (let j = 0; j < 10; j++) {
      for (let i = 0; i < 1e9; i++) {
        sum += i;
      }
    }
    resovle(sum);
  });
};

const server = http.createServer();

server.on('request', async (req, res) => {
  console.log('request');
  if (req.url === '/compute') {
    const sum = await longComputation();
    console.log('finished');
    return res.end(`Sum is ${sum}`);
  } else {
    res.end('Ok');
  }
});

server.listen(3000);

The purpose of longComputation is to simulate long running task, then I make two requests:

  1. to /compute (to perform the long task - takes 3s)
  2. after 1s I send to / - that needs to return just "OK"

but when I make the second request the server not respond until the first one is finish,

**This is the output of the two request - you can see the second request print last until the first proccessed.

  1. request
  2. started
  3. finished
  4. request**

why is that happanning?

Upvotes: 0

Views: 46

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

This is because JavaScript is single-threaded. You will want to read a little about cooperative multi-tasking, which is the multi-tasking model used by JS. Nothing ever happens in parallel in JS unless you use worker thread explicitly (and these are still somewhat new). So your long computation will stall everything in your app, including the server that you want to respond to the second request.

If you really need long-running computations I would either use a worker thread, or, in many cases, think about implementing the computation in a C++ library (which will also be faster). Alternatively you can break down the computation into many logical chunks, and relinquish control between chunks. One way to accomplish that is to use setTimeout(() => processChunk(nextChunk), 1) to start the next chunk.

Upvotes: 1

Related Questions