DEV Community

Vishal Gaurav
Vishal Gaurav

Posted on • Edited on

One (serious) problem with callback in Javascript

Callbacks, these are functions that are passed as argument to other functions. These callbacks are then invoked by function to which it is passed. We commonly pass callback while using function such as setTimeout() and setTimeout().

While callback seem to be obvious in their use, they have a inherent flaw with them. This post is all about this problem which i learnt recently in KyleSimpson's course at Frontend Masters.

Is it the infamous Callback hell?

The first thought that comes to our mind while addressing the problem with callback is callback hell. However this not is not even closer to the problem we have.

Enough of setting the stage, now let's go directly to it. 😅

Inversion of Control

Wikipedia states IOC as:

In software engineering, inversion of control (IoC) is a programming principle. IoC inverts the flow of control as compared to traditional control flow. In IoC, custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as compared to traditional procedural programming

To put simply, IOC is loosing the program flow control from our hands to some external code.

Now let's see how this is possible with callback.

Suppose there is a function for tracking checkout which takes two arguments, first one for product info and second as a callback to be invoked when someone checkouts.

And this is how we call it.

trackCheckout(purchaseInfo,function finish(){
    chargeCreditCard(purchaseInfo);
    showThankYouPage();
});
Enter fullscreen mode Exit fullscreen mode

The problem with passing the callback here is that it's invocation is not in our hand. We are giving the control to the trackCheckout function which is provided with some third party code.

What if the developer of trackCheckout mistakenly calls our callback like this?

function trackCheckout(options,callback){
    process(option);
    callback();
    callback();// 
}
Enter fullscreen mode Exit fullscreen mode

Did you notice that our callback now was executed two times!? This mean that now our end users will get charged twice instead of once and this is the least expected shopping experience.

Further, it can also happen that our callback is not even called which now will put us to loss.

function trackCheckout(options,callback){
    process(option);
    //callback();
}
Enter fullscreen mode Exit fullscreen mode

So, this is how we callback lead of inversion of control, the problem to this is promise which i will cover in some other blog someday.

Thank You

Top comments (0)