Callback in Javascript — ES6

Prelude

What is a Callback?

For what reason do we require Callbacks?

function first(){
console.log(1);
}
function second(){
console.log(2);
}
first();
second();
// 1
// 2
function first(){
// Simulate a code delay
setTimeout( function(){
console.log(1);
}, 500 );
}
function second(){
console.log(2);
}
first();
second();
first();
second();
// 2
// 1

Make a Callback

function doHomework(subject) {
alert(`Starting my ${subject} homework.`);
}
doHomework('math');// Alerts: Starting my math homework.
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}

doHomework('math', function() {
alert('Finished my homework');
}
);
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}
function alertFinished(){
alert('Finished my homework');
}
doHomework('math', alertFinished);

Real world example mapping with Twitter

T.get('search/tweets', params, function(err, data, response) {
if(!err){
// This is where the magic will happen
} else {
console.log(err);
}
})T.get just methods we are making a motivate demand to Twitter

Congrats! You made it!!

--

--

--

Tech evangelist and browser tab hoarder. 👨‍💻 Software Engineer and Google certified Data Analyst. Content about tech, startup, SaaS, finance, etc. #Bitcoin

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

[筆記] Hexo — nexT 基礎配置 (三)

5 Naming Principles Every Developer Should Keep in Mind

What are the rules of naming a variable?

Use the popular cayman theme in React

Introduction to NodeJS

What is Nodejs?

Creating Basic Angular Application in 10 minutes — Part 1

A Committed Intro Guide to ReactJS, Part 3

Referensi Web Penyedia Icon dan illustrasi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Samee Hassan

Samee Hassan

Tech evangelist and browser tab hoarder. 👨‍💻 Software Engineer and Google certified Data Analyst. Content about tech, startup, SaaS, finance, etc. #Bitcoin

More from Medium

Debug values using getters or Proxy

Understanding the Intersection Observer JavaScript API

How to get started with vim(neovim) for web development in 2021

Developer experience working with full-stack Typescript/Javascript/Node.js