1

I want to know that even though the callbacks are done. How will the callbacks and other process on main thread can be executed parallely if the node is single threaded model.

1 Answers1

7

First off, callbacks are not executed in parallel. There is only ever one thread of Javascript execution at a time so there is no actual parallel execution of Javascript code. You can have multiple asynchronous native code operations in-flight at the same time, but when it comes time for them to run some sort of Javascript completion callback, those are run one at a time, not in parallel.

Javascript is an event driven language which means that things like timers, callbacks from asynchronous disk I/O, callbacks from network operations, etc... use an event queue. When the JS engine finishes executing a piece of Javascript and control is returned back to the system, the JS engine pulls the next event off the event queue and executes it. Native code operations can signal that they are complete and want to run a callback by inserting an event into the event queue.

For an async operation like an HTTP request such as http.get(), here's basically what happens:

  1. Your javascript calls http.get()
  2. That call sends the http request and then returns immediately. Whatever callback you passed to http.get() is stored internally by the http module and is associated with that particular network request.
  3. Your javascript code after the http.get() continues to execute until it is done and returns control back to the system.
  4. Then, some time later, the response from the previous HTTP request comes back to the TCP engine. That causes the http module to insert an event in the Javascript event queue to call your completion callback that you previously sent with http.get().
  5. If the Javascript engine is not doing anything else at the moment, then your callback is executed and passed the result response data.
  6. If the Javascript engine is doing something at the moment, then the event sits in the event queue until the current piece of Javascript that is executing finishes and returns control back to the system. At that point, the JS engine checks the event queue and pulls the next event off the queue and executes it. If that is your callback, then you callback is called at that point.

So, various operations such as async disk I/O, network operations, etc... can run in the background because they are being controlled by native code (not by the Javascript engine). That native code has the ability to use threads if required. The fs module uses threads, the net module does not because the native OS already supports asynchronous networking operations.

jfriend00
  • 683,504
  • 96
  • 985
  • 979