Search code examples
node.jsasynchronouscallbackbackground-processchild-process

Does nodejs create background task or child process to execute callback function


Does NodeJS create a background task or child process to execute callback functions? How does NodeJS execute the query below?

MyModel.find({}, function (err, docs) {
  //Do some thing
});

Solution

  • NodeJs implements non-blocking i/o to achieve these callbacks in single thread. It uses an event-loop.

    On demand of data, nodejs registers a callback and send the operation to this event loop. and when data is available, callback is called.

    Say a thread is executing callback A. It keep executing, and say it finds another async task. It registers the new callback B for that async task. Meanwhile waiting for data of B, it start executing some other callback C. Once C is completed. Then it check if data of B is available. If so, executes B. Otherwise executes some other callback D... and so on..

    read this for deep understanding http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/