The basic idea behind using callback is that if we are doing a task and it is taking a longer time to complete. So instead of waiting for this task to be complete we want our node server to process other incomming request.In such situations we can use callbacks.
Callback is a function which is called at the completion of a given task. So it prevents our code to be blocked and allows other code to executed simultaneously.
Let understand this with an example.
Suppose we have to read a file 'sample.txt', and that file contain a large amount of data. So first we create a file test.js , in that file we start reading sample.txt file and then pass the control to the next instruction and read the file in background. Once the file reading is complete it will invoke the callback function.
Example code:
var myfile = require("fs");
myfile.readFile('sample.txt', function (err, data) {
if (err) return console.error(err);
console.log("File reading has been finished");
});
console.log("Hello world!");
Now run the test.js file by following command:
$ node main.js
// Output would be
Hello world!
File reading has been finished
In this manner there will be no blocking and our node server can process a large number of requests, which would not have been possible without using callbacks, that allows us to write asynchronous non blocking code.
0 Comment(s)