Thursday, May 4, 2017

CallBack Functions




CallBack Function

  • Passed as an argument to another function, and,
  • is invoked after some kind of event.
  • Once its parent function completes, the function passed as an argument is then called


Simple example of callback function

This is an simple example for a callback function. 
Steps involved for creating a callback function
  • Define the callback function
  • Define a function which takes the callback function as its input parameter
  • We need to call the callback function within the function, callback();
  • Have a function call and send values to the callback function as parameter.
/*Function callback
  We can pass a function as an argument to another function
**/

//This function is passed as parameter
let x=function(){
    console.log("Called form inside a function.")
}

let y=function(callback){
console.log('Called first.');
callback();
}
//Calling function y with x as  callback function.
y(x);


Function for calculation without callBack

let calculate=function(num1,num2,CalcType)
{
    if(CalcType=="mul")
    {
        return num1*num2;
   }
    else if (CalcType=="add")
    {
         return num1+num2;
    }
}
//function call
var resultAdd=calculate(3,2,"add");
var resultMul=calculate(3,2,"mul");
//Console.log
console.log( "Addition : " +resultAdd);
console.log("Multiplication : " +resultMul);


Same function has been abstracted with callback

In this example, we have abstracted different functions outside the calclib function
Based the on function type we are sending callback function as parameter
//This function can be abstracted using callback
let add=function(num1,num2)
{
  return num1+num1;
}
let mul=function(num1,num2)
{
     return num1*num1;
}
let zero=function(num1,num2)
{
     return 0;
}
//We can use these functions as callbacks
let calcLib=function(num1,num2,callback)
{
    return callback(num1,num2);
}

//Use this function
console.log("Add :"+ calcLib(3,2,add));
console.log("Mul :"+ calcLib(3,2,mul));
console.log("Zero :"+ calcLib(3,2,zero));

Callback using anonymous function

In this example we have a callback with anonymous function.
note: Anonymous functions are functions that do not have a name

//We can use these functions as callbacks
let calcLib=function(num1,num2,callback)
{
    return callback(num1,num2);
}

//Callback using anonymous functions
console.log("Subtract :"+ calcLib(3,2,function(a,b){
    console.log(`value of a ( ${a} ) inside anonymous function`);
    return a-b
}));

Output
C:\Development\NodeProjects\vanilanode>node callbackuse
Addition : 5
Multiplication : 6
Add :6
Mul :9
Zero :0
value of a ( 3 ) inside anonymous function
Subtract :1

No comments:

Post a Comment