a blog for those who code

Saturday, 29 April 2017

Understanding Callback Mechanism in Node.js

In this post we will be discussing about Callback Mechanism in Node.js. A normal callback is an asynchronous equivalent for a function or method which is being called when a task is completed. Callback is sometimes little confusing for a newbie, so through this post we will try to explain the Callback Mechanism in simple way.

We can also termed Callback as a functional programming technique that provides us the advantage of passing a function as an argument to another function.

Let's take an example, we have a function call addNumbers which takes two arguments and returns the sum of it and then we have a function called getResult which calls the addNumbers to get the result back.

var addNumbers = function(a,b) {
 return a + b;
}
function getResult() {
 console.log('Result : ', addNumbers(2,3))
}
getResult();


Now instead of directly calling the getResult function, lets set a timer which will call the result after 2 seconds as shown below :

var addNumbers = function(a,b) {
 return a + b;
}
console.log('Log Started');
function getResult() {
 console.log('Result : ', addNumbers(2,3))
}
setTimeout(getResult, 2000);
console.log('Log Ended');


Now lets go through the callstack generated by JavaScript for the above code. Since the setTimeout method is an inbuilt document method, the method is called in a different context as it is recognized as an asynchronous code and execution of the callstack continues. So you can see instead of printing "Result : 5" after "Log Started" it printed "Log Ended".

ALSO READ : What are Error First Callbacks in Node.js

Since the setTimeout is an asynchronous code, it is being pushed to Web API Stack. Once the time expires i.e. 2 seconds are over, the setTimeout method is being pushed to task queue, from Web API Stack, to get it executed.

This is where the Event Loop comes into picture, on every event emitted in the browser, event-loop keeps on checking for any tasks are prioritized in the queue. Event-Loop retrieves the prioritized task from the and performs the execution when call-stack is empty.

When we use Callbacks in Node.js the only difference it has with the normal JavaScript execution engine that the JavaScript Engine takes use of Web API Stack whereas Node.js has inbuilt Node.js API stack which does almost the similar task as Web API stack.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a comment