Full Disclosure: I am a nodeJS beginner.
Purpose: Test NodeJS express handling multiple requests at the same time, while being blocked on a promise, by using async-await.
Test Strategy: Create a simple nodeJS express server with async get. Open two browser tabs calling the same port. Despite async, both the browser requests are handled sequentially.
Code:
const express = require('express')
const app = express()
var i=0;
async function sleep(ms) {
console.log("inside sleep now")
return new Promise((resolve) => {
setTimeout(resolve, ms)
});
}
app.get('', async (req, res) => {
i++
console.log('Got new request. i count:' + i)
console.log('Thread i:' + i + ' starting to sleep')
await sleep(10000).then((resolve) => {
console.log('I am resolved now')
res.send('Hello Express')
})
console.log('Thread i:' + i + ' awake from sleep')
})
Observed Result: Despite async await, when I open the second browser with the tab, until the first thread is awake, I don't see the request logs for the second browser request.
Question: What am I missing? Can express not handle two browser request at the same time, while being blocked on promise, despite async-await. I must be missing something because I know that nodeJS while being single threaded can handle multiple requests by optimising wait time.