In Javascript it is possible to pass a function as an argument to another function just like we pass a normal variable to a function.
Suppose i have a requirement that i want to call 2 functions one after the other and the second function has to be called after the first function executes successfully.
Lets say my first function to be called is 'function1' and second function to be called on successful completion of this function is 'function2'.
If we write it in this way:
function1();
function2();
The 'function2()' will be called even before 'function1()' has completed its execution, this is because javascript is Asynchronous.
To overcome this problem javascript provides us numerous ways. I am going to solve this problem by passing function name as parameter to the function.
Considering the above scenario where 2 functions are to be called one after the another, but second should be called after the successful completion of the first one.
We will call first function and pass second function as argument to it, which will get called after first function completes its execution.
For ex:-
function function1(func_as_paramater){
console.log('Hello world from function 1');
if ((!(my_function_parameter === undefined)) && (!(my_function_parameter === null)) && (typeof func_as_paramater == "function")) {
func_as_paramater();
}
}
function function2(){
console.log('Hello world from function 2');
}
function1(function2);
Here i called 'function1' and passed function2 as an argument to it. Inside the definition of 'function1' i printed a message on console. And then when its done, i checked whether a function was received in the argument, and if it was, we called that function.
Thus, with the help of function as parameters, we simulated a Javascript callback which only gets executed when first function executes successfully.
Now if function2 received arguments, and using the above approach we had to pass arguments to it, then instead of passing the name of the function directly as an argument we will wrap it in an anonymous function.
For example:-
function function1(func_as_paramater){
console.log('Hello world from function 1');
if ((!(func_as_paramater === undefined)) && (!(func_as_paramater === null)) && (typeof func_as_paramater == "function")) {
func_as_paramater();
}
}
function function2(p1, p2){
console.log('first argument is ' + p1);
console.log('second argument is ' + p2);
}
function1(function(){ function2("arg1", "arg2") });
0 Comment(s)