Saturday, 2 March 2019

How to define callback function in Java script

//How to define callbacks

Define two js files
1. apps.js
2. functions.js

apps.js, is the main js file, which will call many other functions, once of them may be functions.js
withing functions.js , we define  getMessage, and getMessage2 function.


/*apps.js : step by step we are building this function body
--first define a function
  getMessage2();

--define a function as parameter to this function.
  getMessage2(function(){})

--you may also write this as arrow function
  getMessage2(()=>{})

--this function [arrow function]is called callback function, which returns a value in parameter[this callback function body reside here in apps.js ]
  getMessage2((param1)=>{
      console.log(param1)
  })

--once the value is returned into this parameter from callback function, this will be printed 
============================================
functions.js

1. const getMessage2 = function(){}

--callback function passed as parameter here, which was defined in app.js
2. const getMessage2 = function(callback){}

--since callback function has a parameter[see apps.js]
3. const getMessage2 = function(callback){
    callback('Static Param value')
}

4. async functionality addition
const getMessage = function(callback){
    setTimeout(() => {
        console.log('timeout 2 sec')
        callback('Parameter Static Value')
    }, 2000);  
}
*/

No comments:

Post a Comment