1

I've seen something like this asked many times, but I never see a clear answer given.

Given an express server with a block like this:

var express = require('express');
var router = express.Router();    

app.use(async function(req, res, next){
    console.log("REQUEST DETECTED");
    await new Promise(r => setTimeout(r, 5000));
    next();
});

app.use('/', router.get('/', function(req, res, next) {
    // Serve a basic page
});

Consider this timeline

  1. Navigate a browser to the / route
  2. Console logs "REQUEST DETECTED"
  3. Open a new tab to the / route
  4. 5 seconds later, tab 1 displays the page content and the console outputs "REQUEST DETECTED" a second time.
  5. 5 seconds later, tab 2 displays the page content.

What I expected would be

  1. Navigate a browser to the / route
  2. Console logs "REQUEST DETECTED"
  3. Open a new tab to the / route
  4. Console logs "REQUEST DETECTED" a second time.
  5. 5 seconds later, both tabs display the page content.

Can Express not capitalize on time spent awaiting in order to process other requests? And just to be clear, the same thing happens when I await useful work like running a DB query. If one user requests a heavy query, the entire site hangs for every other user. Is there an alternative solution here?

  • You do not call `next()` until after you wait for your middleware to complete, so it has no choice but to wait until you've signaled you're done. You must call next to signal you are ready to proceed. https://expressjs.com/en/guide/using-middleware.html – Chase Jan 19 '22 at 06:51
  • 1
    Are you testing with Chrome by any chance? See [this answer](https://stackoverflow.com/a/66979750/283366) – Phil Jan 19 '22 at 06:52
  • It makes sense that I'd need to call `next()` to resume loading the current page, but it doesn't make sense to me that that would tie up all other incoming page requests. Plus, if instead of spinning uselessly, it's running an important query, if I called `next()` I'd be abandoning the results of the query. – user2536496 Jan 19 '22 at 13:18
  • I see. I'm testing with Brave, and when I test with another device instead of multiple tabs, it seems to work as I originally expected. That's not the case when using a heavy query rather than an idle timeout, but that might have more to do with my database than Express. Thank you! – user2536496 Jan 19 '22 at 13:35

0 Answers0