I was reading Don't Block the Event Loop from the Node.js guide. There was a line saying:
You should make sure you never block the Event Loop. In other words, each of your JavaScript callbacks should complete quickly. This of course also applies to your
await
's, yourPromise.then
's, and so on.
I started to wonder, what if, some API call to the database which I'm await
ing is taking some time to resolve, does that mean that I have blocked the event loop with that await
call?
After that, I started testing some self written codes but after testing I'm still not clear how blocking through await
works. Here are some testing codes:
Assuming, that I'm using express for testing. I understand why making 2 API calls to the /test
route blocks the event loop in this case.
function someHeavyWork() {
// like calling pbkdf2 function
}
app.get('/test', (req, res) => {
someHeavyWork();
res.json(data);
});
But that doesn't happen in this case.
function fakeDBCall() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data);
}, 5000)
})
}
app.get('/test', async (req, res) => {
const data = await fakeDbCall();
res.json(data);
})
This may be because of my lack of understanding of how blocking works in the case of async/await
.