Reputation: 1033
After reading a lot about NodeJS Event loop, I still have one doubt.
In our code, if NodeJS runtime finds any async call, it pushes it to task/message queue which runs on a background thread and V8 keeps executing our further code on main thread. Once that async task has been finished, node checks the call stack for empty. If call stack is empty, then only node brings that callback on main thread for processing. Otherwise it has to wait till call stack is empty.
Up to this point I assume, I am correct.
Doubt: If async task finishes and call stack is not empty, then callback will need to wait for the call stack to become empty. Now suppose, if there are so many calls in my call stack which may take lot of times (less than async task to finish) and async task has been finished earlier, then unnecessary it has to wait for the call stack to become empty.
Has Node been designed in this way only that callback needs to wait for the call stack to become empty ?
Upvotes: 0
Views: 395
Reputation: 111268
If async task finishes and call stack is not empty, then callback will need to wait for the call stack to become empty. Now suppose, if there are so many calls in my call stack which may take lot of times (less than async task to finish) and async task has been finished earlier, then unnecessary it has to wait for the call stack to become empty.
That's right. For example if you call fs.readFile()
and then run a long-running for
loop then if the read file operation finishes before the for
loop finishes, it will still have to wait for the for
loop.
For example consider this code:
let fs = require('fs');
fs.readFile(__filename, 'utf-8', (err, data) => {
if (err) {
console.log('Error:', err.message);
} else {
console.log(data);
}
});
for (let i = 0; i < 1e9; i++);
The readFile
callback will have to wait for the for
loop to finish.
Has Node been designed in this way only that callback needs to wait for the call stack to become empty ?
Yes. You need to make sure that you're not blocking the event loop by blocking the main thread with long running computations that prevent the call stack from getting empty. This is not only Node, this is how all client-side JavaScript works as well.
For more details see this answer:
Upvotes: 1