Simplifying the JavaScript Callback function for .NET developers

Dhananjay Kumar / Wednesday, May 20, 2015
 In JavaScript, functions are objects, and they can:

·         Be passed as an argument to another function

·         Return as a value from a function

·         Be assigned to a variable

Let’s assume that you have a JavaScript function (let’s call it function A) with the following properties:

1.       Function A takes another function (let’s call this one function CB) as one of the parameters.

2.       Function A executes the function CB in its body.

In the above scenario, function CB is known as the Callback function. Let’s learn more about it using the following code:
 
function A(param1, param2, CB) {
 
    var result = param1 + param2;
    console.log(result);
    CB(result);
 
}
 
Here we’ve created a function A , which takes three parameters. You will notice that last parameter - CB - is a function, which is being called inside the body of function A. Next we’ll call function A as shown the below listing:
 
function CallBackFunction(result) {
    console.log(result + ' in the CallBack function');
}
 
A(5, 7, CallBackFunction);
 
Here we’ve created a function named CallBackFunction (You can name it whatever you’d like) and we’ve passed it as the third parameter in function A. In its body, function A is executing the passed CallBackFunction.
Another way to pass a Callback function is the anonymous function. See the example here:
 
A(5, 7, function (result) {
 
    console.log(result + ' in the CallBack function');
});
 

How does the Callback function work?

In the called function, we pass the definition of the callback function. Let’s consider the example we took above:

1.       In function A, we are passing the definition of the callback function

2.       Function A has information about the callback function definition

3.       Function A calls the callback function in its body

4.       While calling function A, we pass the callback function

5.       The callback function can be either named or an anonymous function

 

Optional callback function

What would happen if we don’t pass a third parameter (i.e. a callback function) in function A? In that case, an exception will be thrown stating that “undefined” is not a function. A JavaScript function may take more or less arguments. When we call a JavaScript function with less parameters, “undefined” gets passed for the parameters which are not passed. So in the above scenario for function A, when we don’t pass the third argument, undefined gets passed and we get the exception that undefined is not a function.
We need to be sure about following three points while creating a callback function:

1.       Make sure the callback function is passed

2.       If the callback function is not passed, then handle the exception

3.       Ensure that a callback only function is passed, not any literal or other kind of object

We can implement the points above in the snippet below:
 
function A(param1, param2, CB) {
 
    var result = param1 + param2;
    console.log(result);
    if (CB !== undefined && typeof (CB) === "function") {
        CB(result);
    }
 
}
 
In the above listing, we are checking:

1.       Whether the value of CB is undefined or not

2.       Whether the type of CB is a function or not

By checking the two points above, we can make the callback function optional.
 

Callback with asynchronous call

In JavaScript, sometimes you might be required to work with asynchronous methods, for example when:

1.       Reading or writing a file system

2.       Calling web services

3.       Making an AJAX call, etc

The tasks mentioned above can take time and block the execution. While reading from the file system or making an AJAX call, you don’t want to wait. You’ll want to perform following operations as asynchronous. We can use a callback function here to handle the asynchronous operation, so the callback function will be executed when the asynchronous call is completed.
Let’s say that you need to consume service to fetch the data. Without AJAX that can be done as shown in the listing below:
 
getData('serviceurl', writeData);
 
function getData(serviceurl, callback) {
    //service call to bring data
    var dataArray = [123, 456, 789, 012, 345, 678];
    callback(dataArray);
}
 
function writeData(myData) {
    console.log(myData);
}
 
In the AJAX call we can use callback function as shown in the listing below:
 
function GetUser(serviceurl, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () // can replace this with callback
    {
        if (request.readyState === 4 && request.status === 200) {
            callback(request.responseText); // using the callback
        }
    };
    request.open('GET', serviceurl);
    //req.setRequestHeader('X-Requested-With', '*');
    request.send(null);
}
 
function DisplayData(data) {
    console.log(data);
}
 
GetUser('serviceurl', DisplayData);
 
As you see here, we’re using the callback function to print the data. We can even replace the function called on onreadystate with the reusable callback function.
That’s about all I’ve got for this post about the callback function – I hope you find it useful, thanks for reading!