Callbacks

Callbacks

In my previous article, I explained the difference between synchronous and asynchronous JavaScript. In this piece, I’ll be explaining callback functions, in relation to asynchronous JavaScript.

Recall, in asynchronous JavaScript, the execution of code is NOT sequential. A task could be initiated now, but finished later on after something else has happened. Therefore, a callback argument is provided to the function that does something asynchronously. The callback argument will be executed/called once the asynchronous task is complete.

Note: the execution of a callback function is dependent on whether or not the asynchronous task is complete.

Example:

To illustrate this simply, consider the built-in setTimeout() JavaScript function:

Syntax:

setTimeout(callback_function, time);

In the setTimeout() function, the given callback function is only executed once the time specified has elapsed.

Below, the statement is logged once the 5seconds specified have lapsed.

setTimeout(() => {
    console.log("5 seconds have lapsed");
}, 5000);

Callback Hell

Now consider a practical case whereby;

  1. We want the user to input data
  2. Using the data given by the user in (1), we fetch some data from an API
  3. Next we fetch more data using data received in (2)
  4. And finally we display this data

The code will look somehing like this:

getUserInputData(() => {
    fetchUserData1((res)) => {
        fetchUserData2((res) => {
            displayData((res) => {
            }); 
        });
    });
});

Note that as we nest the functions providing the callbacks, the code becomes more and more complex, messy, and much harder to understand, this situation is referred to as callback hell. To solve this, the concept of promises was introduced in ES6 allowing a much cleaner code style.

In conclusion, callbacks are an essential part of asynchronous JavaScript. And even with the introduction of promises and async/await, callbacks are still necessary depending on what is to be achieved.

Any thoughts and comments, would love to hear those!