0

I'm starting to create an webapi with Node Js and Express.

Then the following question came up :

If I have a function that will handle the / request like:

router.get('/', (req, res, next) => {
  pool.query("select * from users").then((data) => {
    setTimeout(() => {
      res.json(data.rows);
    }, 5000);
  }).catch((err) => {
    res.json({
      error: err
    });
  });
});

Considering that the database query takes longer than expected, will other users be able to request the same route at the same time ? Or will express block it until it has a response to the first request?

**The timeout function inside the then() block is just to illustrate what I mean.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Diego Barreto
  • 195
  • 3
  • 13
  • Been asked many times before [What is non-blocking or asynchronous I/O in Node.js?](https://stackoverflow.com/questions/10570246/what-is-non-blocking-or-asynchronous-i-o-in-node-js) and [Node.js - single thread, non-blocking?](https://stackoverflow.com/questions/29911478/node-js-single-thread-non-blocking) just to name a few. Plenty of far more detailed explanations out on the wider internet. – Neil Lunn Apr 16 '18 at 00:48

1 Answers1

1

Other users will be able to request the same route at the same time.

Node/Express handle concurrent requests automatically. They run in an event driven model meaning nothing blocks and everything runs concurrently. Javascript is single threaded so each program runs on a single core yet every line of code executes without waiting for anything to return.

eli-bd
  • 1,533
  • 2
  • 17
  • 35
  • Yeah, the thing is when i put a timeout function and try to get the data twice in a row before the timeout, the two requests takes two times the specified timeout, and it should take a little more than one, shouldn't it? Because if request one starts and takes 10 seconds to execute and after 1 second the second request starts and also takes 10 seconds. It should take 10+1 seconds to execute both requests, but instead its taking 10+1+10 seconds... – Diego Barreto Apr 16 '18 at 01:25