Skip to main content

Javascript: Callback and High Order Function

CALLBACK

A callback is a function that gets invoked after an asynchronous result appears. a callback function is an async function argument.
- Asynchronous code result handle using callback and promises.

// callback 

  • function
  • function with argument  // ---argument :// if a function pass-through function as an argument, it is higher-order function. function needs to be called in order to execute. a callback is used when calling a function asynchronous 
What is a Callback or Higher-order Function?
  • A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction. A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern.
  • High-order function is a function that takes a function as an argument, or returns a function. Callback function also known as high order function. Functions are actually first class object. pass object into two function : arg and callback. 
  • Callback Hell:  is when people try to write JavaScript in a way where execution happens visually from top to bottom. Callback hell is any code where the use of function callbacks in async code becomes obscure or difficult to follow.

Async Example:

function lendMoney(){
     return 100;
}


function payCollegeFee(fee, cb){
     console.log('Fee received in college');
     setTimeout(function(){
     console.log('It takes 5 sec to prepare admit card');
     cb('admit cart');
}, 5000);
}
console.log('Lend money result', lendMoney());


function payFee(cb){
console.log('My son asked for fee but papa dont have money'); setTimeout(function(){
console.log('papa received salary');
console.log('papa was requested for fee pay');
console.log('papa must pay fee now');

cb(4000);
}, 8000);
}

console.log('Ask papa for free')

//payFee call back
payFee(function (fee){
      console.log('I received money from papa');      var myMoney = fee - 1000;
      payCollegeFee(myMoney, function(admitCard){
      console.log('admission card received>>', admitCard); });
});
console.log('I go to school');
console.log('I play guitar in school');


Note:
Run in nodejs: node module.js
Output: Lend money result 100
Ask papa for free
My son asked for fee but papa dont have money
I go to school
I play guitar in school

Callback Example 1: 

Callback Example 2:

Output: "Starting my math homework."
"Finished my homework."

Callback Example 3: 







Comments

Popular posts from this blog

Deploy react app on digitalocean using nginx

Source:  https://www.learnwithjason.dev/blog/deploy-nodejs-ssl-digitalocean/ Source:  https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04 Source:  https://www.youtube.com/watch?v=vRrhQwNixlc https://www.youtube.com/watch?v=pyxXCwgWdMw https://dev.to/xarala221/the-easiest-way-to-deploy-a-react-web-application-2l8a 1. Create a new droplet on DigitalOcean. Choose the $5/month option with Ubuntu 16.04.1 x64. Select a region closest to your users. 2. Finally, add your SSH key and ls -la ~/.ssh # This copies the key so you can paste with command + V pbcopy < ~/.ssh/id_rsa.pub # This prints it in the command line for manual copying cat ~/.ssh/id_rsa.pub   3.  Add your SSH key to the droplet Click “Add SSH Key” to save it, then make sure it’s selected, name your droplet, and hit the big “Create” button to get your server online. Your n...

Github Tutorial

GitHub brings together the world's largest community of developers to discover, share, and build better software. Delivered through software as a service(SAAS) business model 2008 by linus (Owner: Microsoft)  #Create New Repository in Github New Repository Add Repository Name and description Public / Private, initialize this repo with Read Me Create repository create a new repository on the command line echo "#test" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/sinuna/test.git git push -u origin master …or push an existing repository from the command line git remote add origin https://github.com/sinuna/firstRepository.git git push -u origin master …or import code from another repository You can initialize this repository with code from a Subversion, Mercurial, or TFS project. Initialize Repo $ git init Clone Repo $ git clone https://github.com...

NodeJS: Request and Respose Objects

# req Objects - req - req.body, req.queries, req.validationerrors - res.headers, req.users, req.file, req.assert - req.params, req.checkbody #res Objects - res.send, res.end, res.json, res.render, res.status, res.sendStatus # - .limit(4) //limit only upto 4 docs - skips(3) //skip first 3 docs - exe //query build and then execute, it is also callback function of mongoose. - sort({_id: -1}) //for decending order - populate('userId') //populating data inside the reference.