Synchronous programming means that the code runs in the sequence it is defined. In a synchronous program, when a function is called and has returned some value, only then will the next line be executed
Note: Asynchronous functions will run and execute only after all the synchronous functions have been executed. Until then, they will be processed in the background
Call stack, Node APIs and Callback queue. All these together constitute the NodeJS environmen
For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case.
A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program. This data structure has only one open end to add or remove top items.
When the program starts executing, it first gets wrapped inside an anonymous main() function. This is automatically defined by NodeJS. So main() gets pushed first to the callback stack.
All these values are stored in memory.
After this function gets executed, it is removed from the callback stack.
it will not get processed in the callback stack.
It is then added from the callback stack to the Node APIs where an event is registered and a callback function is set to get processed in the background.
Then another callback function gets set to be processed after a 2 second timeout in the background. Up until this point other functions can be performed.
This is called non-blocking behaviour where all the synchronous functions are processed and executed first and asynchronous functions are processed in the background while waiting their turn to get executed.
In the background, all the asynchronous functions get processed and their callbacks are stored in the callback queue. The one which is processed first will be added first in the queue for execution in the callback stack
Asynchronous functions cannot run inside a callback stack until it gets
That means that after main() is removed from call stack, only then can all asynchronous functions start executing.
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.