Callback in javascript
-
date_range 18/07/2015 00:00 infosort label
A callback function is a function that is passed to another function as parameter and the callback function is called (or executed) inside another function.
e.g :-
How to make sure that Callback is a function before executing it??
It is always wise to check that the callback function passed in the parameter is indeed a function before calling it. Also, it is good practice to make the callback function optional.
Let's refactor the above code as follow :-
How to call a callback function??
Now we have to use this callback function after executing func1 function. So define callback inside func1. Normally we call a function using just its name and pass arguments inside it but in this case we define function as second argument.
e.g :-
e.g :-
var func1 = function(args ,callback){
}
When we pass a callback function as an argument to another function, we
are only passing the function definition. We are not executing the
function in the parameter. In other words, we aren’t passing the
function with the trailing pair of executing parenthesis () like we do
when we are executing a function.How to make sure that Callback is a function before executing it??
It is always wise to check that the callback function passed in the parameter is indeed a function before calling it. Also, it is good practice to make the callback function optional.
Let's refactor the above code as follow :-
var func1 = function(args ,callback){
.......
if (typeof callback == "function") {
callback();
} else {
console.log("No callback defined");
}
}
How to call a callback function??
Now we have to use this callback function after executing func1 function. So define callback inside func1. Normally we call a function using just its name and pass arguments inside it but in this case we define function as second argument.
e.g :-
func1(args ,function(){
console.log("Call back will executed after fun1 returns the result");
});
Source :- http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/#