NodeJS event loop internal working

六眼飞鱼酱① 提交于 2019-12-12 02:16:29

问题


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 ?


回答1:


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:

  • what is mean by event loop in node.js ? javascript event loop or libuv event loop?


来源:https://stackoverflow.com/questions/42531783/nodejs-event-loop-internal-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!