Nodejs Callback Concept
Expert-led Courses: Transform Your Career – Enroll Now
In this tutorial, we will be discussing Nodejs callback concept and its type in detail with code and examples.
What is Callback function in Nodejs?
Callback is like a function. Sometimes when a task is completed, a function is called and this function is known as callback function. Using callbacks, nodejs can process the requests without waiting for the results of other functions.
Working of Nodejs Callback:
The function contains the callback function as its parameter, now since the callback function is present inside a function it can be executed whenever it is required.
Nodejs Synchronous functions:
This function blocks the thread until this function itself executes completely. If we are reading a very large file using the synchronous approach then it will take some time and rest all the tasks will have to wait until the completion of reading the file. Look at the example code of blocking callbacks below to see how it behaves.
Nodejs Asynchronous functions:
This function does not block the thread. Even when a function is not completely executed other codes can perform their task parallely. Here two or more tasks run simultaneously. Look at the example code of non-blocking callbacks below to see how it behaves.
Types of callback in Nodejs:
1) Blocking callbacks
2) Non-Blocking callback
Nodejs Blocking callbacks:
For demonstrating the blocking callbacks we have created a DataFlair.txt file containing “Welcome to DataFlair”, next in the index.js add the below code of blocking callbacks
var fs = require("fs"); var data = fs.readFileSync('DataFlair.txt'); console.log(data.toString()); console.log("Program Ended");
Output:
From the output, you can observe that it has first read the file and then the subsequent codes were executed i.e the reading of file has blocked the execution of other lines.
Nodejs Non-Blocking Callbacks:
In non-blocking callbacks the other codes will keep executing and will not wait for the completion of the callback function.
Code of non blocking callbacks:
var fs = require("fs"); fs.readFile('DataFlair.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); console.log("Program Ended");
Output:
Here we can see that the last line got printed first and then the other codes were executed. It is happening like this because when the file system was reading the text file the execution of other codes did not stop, hence the last line got executed first and then when the result of the callback was ready, it got executed.
Conclusion:
Observing the above outputs we can see that blocking code executes sequentially whereas a non blocking code does not. And also most importantly if some block of code needs to use the result of some other function then we should write it in a sequential approach.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google