Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does node.js event loop remember that it needs to call back once the long running operation is complete?

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 ?

like image 203
user3769778 Avatar asked Oct 20 '22 05:10

user3769778


1 Answers

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).

like image 167
Bergi Avatar answered Oct 24 '22 10:10

Bergi