As iam exploring Nodejs,i need to know what's a callback?.Can anybody help me.Since i have referred many blogs and tutorials.But still iam not clear.Can anybody explain with simple example and refer forums related to this.
Thanks
As iam exploring Nodejs,i need to know what's a callback?.Can anybody help me.Since i have referred many blogs and tutorials.But still iam not clear.Can anybody explain with simple example and refer forums related to this.
Thanks
A callback is just a function that you call when an action has taken place. For example:
var myCallback = function(){
console.log("Callback Run");
};
setTimeout(myCallback, 1000);
Callbacks are typically used in asynchronous code (such as Ajax calls). The code is passed a function to run when it completes, such as this jQuery:
var doAnAjaxCall = function(success_callback, fail_callback){
$.ajax({
url: 'test.html',
success: function(data){
data.date = new Date(data.date);
callback(data);
},
fail: fail_callback
});
},
okCallback = function(data){
console.log(data.date);
},
failCallback = function(){
console.error(arguments);
};
doAnAjaxCall(okCallback, failCallback);
A very simple example can be:
function sum (a, b, callback) {
callback (a + b);
}
You can call the function sum
in this way:
sum (1, 1, function (res) {
console.log ('Result of the sum is ' + res);
}
As you can see from the code above, the actual parameters are: