A function pass as a argument into another function is called Callback function. In Nodejs Asynchronous operation is handled by callback function.
The callback is designed for Asynchronous operations if you have a simple function that is synchronous. It means not necessary to use a callback on this simple function.
function userDetails(callback) {
var name = 'John';
callback(name);
}
function greeting(name) {
console.log('Hello ' + name);
}
userDetails(greeting);
Note:- In above example greeting function pass as a argument into userDetails function.
If you want to read a file in the synchronous manner then there is no need callback function.
To read a file in the synchronously manner.
var fs = require("fs");
var fileData = fs.readFileSync('inputFile.txt');
console.log(fileData.toString());
Note:- where fs is a library which is used to handle file-system related operations.
If you want to read a file in the asynchronous manner then there is need of callback function.
To read a file in the asynchronously manner.
var fs = require("fs");
fs.readFile('inputFile.txt', function (err, fileData) {
if (err) return console.error(err);
console.log(fileData.toString());
});
Note:- where fs is a library which is used to handle file-system related operations.
What is callback Hell?
if you need to make callback after callback like nested callback then it is very difficult to read and understand the code then we can say this situation is called Callback Hell.
Example:-
getData(function(a){
getMoreData(a, function(b){
getMoreData(b, function(c){
getMoreData(c, function(d){
getMoreData(d, function(e){
...
});
});
});
});
});
What is Error First Callback?
It is really only two rules for defining an error-first callback:
1. The first argument of the callback is reserved for an error object.
2. The second argument of the callback is reserved for any successful response data.
fs.readFile('/foo.txt', function(err, data) {
// TODO: Error Handling
if(err) {
console.log('Unknown Error');
return;
}
console.log(data);
});