Javascript : Callback

What is a Callback?

Simply put: A callback is a function that is to be executed after another function has finished executing – hence the name ‘call back’.

More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

Why do we need Callbacks?

For one very important reason – JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.

Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.

Create a Callback

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

Example 2 :

//callbacks
let arr = [1,2,3,4];
function callback(arr1){
    setTimeout(()=>console.log(arr1),5000);
}
function consoleLog(arr,callback){
    return callback(arr);
}

consoleLog(arr,callback);

//promises
let flag = 1;
let p = new Promise((resolve,reject)=>{
    if(flag == 1){
        setTimeout(()=>resolve("flag is one"),3000);
    }
    else{
        reject("Not 1");
    }
})
// .then((result)=>{
//     console.log("Successful Promise:"+result);
// }).catch((err)=>{
//     console.log("Rejected Promise:"+err);
// });

let p1 = 50;
let p2 = new Promise((resolve)=>{
    resolve("P2 is successful");
})

Promise.all([p,p1,p2]).then((result)=>{
    console.log("All promises are successful:"+result);
}).catch((err)=>{
    console.log("At least one of the promises failed:"+err);
});

Typescript Example

function addAndHandle(n1: number, n2: number, cb: (num: number) => void) {
	const result = n1 + n2; 
	cb(result)
}

//addAndHandle(10, 20, () => {})
addAndHandle(10, 20, (result) => {
	console.log(result)
})

A real world example

The only reason the code in that article works is because of Twitters API. When you make requests to an API, you have to wait for the response before you can act on that response. This is a wonderful example of a real-world callback. Here’s what the request looks like:


T.get('search/tweets', params, function(err, data, response) {
  if(!err){
    // This is where the magic will happen
  } else {
    console.log(err);
  }
})
  • T.get simply means we are making a get request to Twitter
  • There are three parameters in this request: ‘search/tweets’, which is the route of our request, params which are our search parameters, and then an anonymous function which is our callback.

A callback is important here because we need to wait for a response from the server before we can move forward in our code. We don’t know if our API request is going to be successful or not so after sending our parameters to search/tweets via a get request, we wait. Once Twitter responds, our callback function is invoked. Twitter will either send an err (error) object or a response object back to us. In our callback function we can use an if() statement to determine if our request was successful or not, and then act upon the new data accordingly.

The return value of the inner function becomes the argument of the outermost function and so on.

AJAX call make asynchronous to synchronous

Method 1 : Using ‘async:false’

//Declaring the function
var myData = 123
var myFunction = function (myData) {
    var returnValue = null;
    $.ajax({
        type: 'GET',
        async: false,
        url: "https://reqres.in/api/users/2",
        //data:{data:myData},
        success: function (r) {
            returnValue = r;
        }
    });

    return returnValue;
}

//Calling the function
var theResult = myFunction(myData);
console.log(theResult);

Method 2 : Ajax Call using Callback method

//Declaring the function

var myFunction = function (myData, callback) {
    var returnValue = null;
    $.ajax({
        type: 'get',
        //async: false,
        url: "https://reqres.in/api/users/2",
        //if we do post call , there only need this myData
        //data:{data:myData},
        success: function (r) {
            callback(r);
        }
    });
}


//Calling the function
var theResult = myFunction(123, function (res) {
    // deal with it..
    console.log(res);
});

Callback Alternative Syntax

fs.readFile('/etc/hosts', function(err, contents){
	console.log(contents)
})

//SAME AS Syntax

var callback = function(err, contents) {
	console.log(contents);
}
fs.readFile('/etc/hosts', callback)

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *