How node.js prevents blocking code ?
Blocking and Non-blocking operations: Blocking operations refer to the pieces of code that block the execution of other code until they are completed. While non-blocking operations allow further pieces of code to execute without making them wait and use callbacks when they are completed.
Thus, blocking code can be said to work synchronously while non-blocking code works asynchronously. While discussing non-blocking code, we come up with a term called callback. The callback is a function that is invoked when a process completes its execution and wants to continue its normal execution with the outer function.
Node and Event Loop: Now we know what blocking and non-blocking operations are, we can discuss how node prevents blocking code. Node uses a single thread, which means one task can be executed at a time. This is done by using a stack. While reading the code from top to bottom, each instruction is pushed into a stack and when its execution is completed, it pops out of the stack. Now we may come across an instruction/function that will take a longer time to execute which can result in the delay in popping the stack and execution of further statements.
So what Node.js allows is the use of Event Loop. Each time when we encounter such a situation, the process causing the delay is offloaded from the stack and the execution of that process continues parallel to further execution of the main code. Thus, the callback for that function is pushed into a task queue and the code continues to execute asynchronously. When the process completes its execution, the callback function returns the desired output from that process and resumes normal execution.
Example: Let’s consider an example that will demonstrate how the event loop works.
Run the index.js file using the following command.
Geeks For Geeks
Explanation: Although the instruction to log Geeks is before the instruction to log For, that is not the order they are getting logged in the console. What happens is when the setTimeout function is called, the timer to wait for 3 seconds is triggered. But this timeout will not happen while the function is in the call stack, and instead is handled by Node API. Thus, further instructions get processed as they should and when the timer turns to zero, the callback function will be invoked and the result from the function will be returned.
Please Login to comment...