I am pretty new to NODE.JS. I read that in node.js only single event loop (as its single threaded) exist.
now suppose, the case is as such, end users makes requests and below piece of code is a part of module user is trying to run:
....some code before......
longRunningOperation(argumentsForLongOperation, callbackMethod(argumentsForCallBack));
....some code after......
As nodejs is async, event loop will call longRunningOperation
and move to the next lines of codes to execute if any in module.
Now when longRunningOperation
returns, how does my event loop knows that it should now run callback as the longRunningOperation
has returned.
In java we have method stacks, and the thread is stuck at the point where longRunningOperation
is called so when the function returns, the thread resumes from then on completing the call stacks.
My question is how in node.js the event loop comes to know that longRunningOperation
has returned and it needs to call now callBack()
function ?
It doesn't remember. The longRunningOperation
itself needs to tell the event loop a) that it holds onto callbackMethod
and b) when it is finished that the callback should be executed. This is why only native functions are asynchronous, normal javascript code cannot access the event loop. And they do return immediately as well, they typically are asynchronous even on the system level. If they're not, they will have to spawn a thread for their computation (still returning immediately from the spawning).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With