Express controller code doesn’t seem to be running asynchronously

This is a much simplified version of an ExpressJS controller I have.

I put the sleep function in to test loading indicators on my front-end and I was very surprised that when calling this function twice simultaneously from the browser, instead of both taking 5 seconds they took a total of 10 seconds to complete.

function sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms))
}


const get =  async (req: Request, res: Response, next: NextFunction) => {

    await sleep(5000)

    res.status(200).json({})


}

export default get

Express controller code doesn't seem to be running asynchronously

My understanding was that because I am using all asynchronous code the first one would wait for the timeout while other requests to the server continue to be served.

Whilst I don’t use a sleep function everywhere else I do have lots of async code and I’m worried that each time I make a long DB call my API is being stopped from serving other requests, but this doesn’t fit with my understanding of how Node/Express works, so am I just doing something wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This might be a client-side issue with the browser caching.

I set up a test server based on your sample (side note, always helpful to include a Minimal, Reproducible Example…makes it quicker and easier for others to troubleshoot/reproduce your problem)

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

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

app.get('/tst', async (req, res, next) => {
  await sleep(5000);
  res.status(200).json({});
  res.end();
});

app.listen(3000);

When I tried two fetches, I saw the same thing as you, they appear to run in serial: one finished in 5s, the other in 10s.

But then when I disabled the browser cache, they ran in parallel, both finishing at the exact same time:

fetch('/tst', {cache:'no-store'});
fetch('/tst', {cache:'no-store'});

In a “real world” environment this probably won’t matter much, since you’re probably more concerned about different users. In that case it won’t matter, since they’re not sharing a cache.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x