How to Create the Callback Function in JavaScript ?

Now the first question is what is the callback function ? What is the uses of the callback function ? Where can I use the callback function ? How we can create the callback function in JavaScript?

Note: Now most of the browser is supporting JavaScript ES6, So it is better to use the Promise concepts which is come in picture in JavaScript ES6.

What is the callback function ?

Callback Function means, A function is fired ( or execute or call ) by the called function, when it’s task is completed. The called function will call the different – different callback function depends on the situation or the results of it’s own process like, it’s task was successfully completed or not ? or any error is executing while working it’s own task.

In Other language you can also say that callback function is simple notification system for the calling function, so the calling function will know the exact status of the called function’s task.

What is the uses of the callback function ?

Callback function is used when you have to perform the async task likes getting data from the server or processing the time consuming task.

It is also used when you want to perform some task on the results of the called function or in between the task of the called function like you want to display the data coming from the server using the async AJAX request.

In simple language I want to say that you can use the callback function mechanisms, when you are performing the multiple async task at the same time, and you does not know whats the exact time required by this async task and you have to perform some extra task on the results of that async task.

Where I can use the callback function ?

  • Performing the multiple async task.
  • Performing the long time consuming task.
  • Performing extra task on the results of the async task.

Steps of the creating callback function.

  1. First we have to create the function for the async task or the long time consuming task.
  2. After the we have to create callback function ( success callback function, error callback function, task status callback function) which is call by the called function.
  3. Now we have to call the function and have to pass all the callback function as the arguments of it.
    So now this callback function will be call by the called function on the status of it’s own task.
  4. And we have to write our code for the extra task inside the callback function that we want to do on the results of the async task.

Syntax:

function asyncTask(onSuccess, onError, result) {
	// ASYNC TASK OR LONG TIME CONSUMIG TASK.
	if (result == true) {
		onSuccess("Task is successfully completed!!!");
	} else {
		onError("Sorry, Something goes wrong!!!");
	}
}

function SuccessFunction(data) {
	// SUCCESS CALLBACK FUNCTION.
	alert(data);
}

function ErrorFunction(data) {
	// ERROR CALLBACK FUNCTION.
	alert(data);
}

asyncTask(SuccessFunction, Error, true); // Task is successfully completed!!!
asyncTask(SuccessFunction, ErrorFunction, false); // Sorry, Something goes wrong!!!

In above code I created the asyncTask function, that will perform the async task like getting data from the server and call the callback function as per it’s task result.

asyncTask function is getting the 3 arguments,

1st argument is the success callback function that is SuccessFunction

2nd argument is the error callback function that is ErrorFunction.

3rd is argument is not required, But I am passing that argument because the I does not performing some task in the asyncTask function so there will be no result. If no result than no callback function is called. So here I am passing the pre-determinate result, which is true or false.

If I am passing the true than success callback function is called or if I passed the false than error callback function is called.

After that I created two callback function that is SuccessFunction and ErrorFunction, Here we have to write our code for the performing extra task on the result.

After that I called the asyncTask function with the pre-determinate results and with the callback function name.

Method 1:

Let’s Create a function for the addition which will calculate the addition of all the numbers and call the success callback function if the addition is successfully completed, other wise it will call the error callback function if the addition is not successfully completed like if we pass the string in place of numbers than it will call the error callback function.

function Addition(onsuccess, onerror) {
    if (arguments.length >= 2) {
        var num = 0, total = 0, bHaveError = false;
        for (var i = 2; i < arguments.length; i++) {
            num = parseInt(arguments[i]);                    
            if (num != arguments[i]) {
                onerror("Invalid number: " + arguments[i]);
                // Here is the error callback function is called
                // when the task performing by the Addition() function is 
                // get something wrong or task is not completed successfully.
                bHaveError = true;
                break;
            }
            total += num;
        }
        if (!bHaveError) {
            onsuccess(total);
            // Here is the success callback function is called
            // when the task performed by the Addition() function is successed
        }
    } else {
        return "Invalid arguments!!!";
    }
}

function SuccessFunction(total) {
    alert("Total is: " + total);
}

function ErrorFunctiom(msg) {
    alert("Error Occured: " + msg);
}

var result = Addition(SuccessFunction, ErrorFunctiom, 1, 2, 3, 4, 5);
// Total is: 15

if (result != undefined) {
	alert(result);
}

result = Addition(SuccessFunction, ErrorFunctiom, 1, 2, 3, 4, 5, "15CX");
// Error Occured: Invalid number: 15CX

if (result != undefined) {
	alert(result);
}

result = Addition(SuccessFunction, ErrorFunctiom);
// Total is: 0

if (result != undefined) {
	alert(result);
}

result = Addition();
// Invalid arguments!!!

if (result != undefined) {
	alert(result);
}

If you just notice above that every time we have to pass the callback function name to asyncTask function, so it is very complicated thing. You have to remember every time that you have to pass the callback function to the asyncTask function.

Method 2:

Let’s create the callback function in another way. Personally It is my favourite to create the callback function mechanisms.

function Arithmetic() {

    this.Error = function (msg) {
        // This is Error callback function,
        // It will be override by Arithmetic class's object.
    }

    this.Success = function (total) {
        // This is Success callback function,
        // It will be override by Arithmetic class's object.
    }

    this.Addition = function () {
        var total = 0, num = 0, bHaveError = false;
        for (var i = 0; i < arguments.length; i++) {
            num = parseInt(arguments[i]);
            if (num != arguments[i]) {
                bHaveError = true;
                this.Error("Invalid Number: " + arguments[i]);
                break;
            }
            total += num;
        }
        if (!bHaveError) {
            this.Success(total);
        }
    }
}

var airth = new Arithmetic();

airth.Error = function (msg) {
    // This is error callback function,
    // Here we have to write code for extra work on the result
    alert(msg);
}

airth.Success = function (total) {
    alert("Total is: " + total);
}

airth.Addition(1, 2, 3);
// Total is: 6

airth.Addition();
// Total is: 0

airth.Addition(1, 2, 3, "15X");
// Invalid Number: 15X

Benefits of Method 2 to create the callback function is that, We does not have to provide the name of the callback function to addition function every time, We simply have to override the error and success callback function of it.

Step of the Method 2 to create the callback function.

  1. Create the class with the callback function and Addition function.
  2. Create the object of that class.
  3. Override the Success and Error callback function which is declared inside the Arithmetic class.
  4. And call the addition function as many as times you want, without passing the callback function name.
  5. Addition function will be call the callback function based on the it’s result.

Note: Now most of the browser is supporting JavaScript ES6, So it is better to use the Promise concepts which is come in picture in JavaScript ES6.

I hope you enjoyed this article, Please comment down your review about this.

Happy Coding!!!

🙂