DEV Community

Cover image for CALLBACK FUNCTIONS
G U BHARATH CHANDRA
G U BHARATH CHANDRA

Posted on

CALLBACK FUNCTIONS

What is a callback function? πŸ€”

As you might already know in javascript we can pass functions as arguments to another function.
βœ”οΈ will explain why you would want that later in this post.

So, yeah a callback function is a function that is passed as an argument to another function [which is called a higher order function] to be called back at a later time.

Let's see an example πŸ˜ƒ


function Higher_Order_function(function(){
        setTimeout(function(){
            console.log('Served!');
        }, 2000);
    }
}

Enter fullscreen mode Exit fullscreen mode

As you can see, here we are calling a function called Higher_Order_function and expecting it to log Served after 2s βŒ›.

It is important to know that javascript is Single Threaded. and synchronous [on the barebones]. That means it's not going to stop running for anything.

We can use ajax , callbacks , async + await , promises to write asynchronous javascript code.

Let's dig deeper ⛏️

Let's learn a few things on how javascript handles code so that we can dig a little deeper into how callbacks work.

βœ”οΈ CALL STACK
βœ”οΈ WEB API
βœ”οΈ CALLBACK QUEUE

Whenever javascript needs to excecute a function or a statement, it puts it into the call stack. After calling the function, it decides based upon the function wether it's a web api and if there is something which needs to be queued (callback queue) [remember javascript is single threaded].
Web apis just means that it needs to be handled asynchronously because we are not sure when we might receive the information needed from the api
ex: an external api, event loop , or basically anything we need to wait for.

Thanks to PHILIP ROBERTS for the visualization tool. You can see that in action by visiting this link. πŸ”°

Why use callback functions?

The idea here is to queue up the tasks which are currently waiting for something else to be resolved [Say, response from an external api] so that the Call Stack is free for the normal tasks to run. So, callbacks are useful for writing some asynchronous code when needed.

But it's not all butterflies and sunshine!

Have you ever heard of Callback Hell?

Well, the name is no mistake. There is an entire website dedicated to it http://callbackhell.com/ ℹ️.

It basically is a conundrum where we end up writing some asynchronous code using callbacks but chained and entagled to each other which makes it difficult for us to debug or even understand what's happening.
Huh! feels like hell 😨

Let's see that with an example:


getData(function(x){
    getMoreData(x, function(y){
        getMoreData(y, function(z){ 
            ...
        });
    });
});

Enter fullscreen mode Exit fullscreen mode

More on this here:

Can someone give a clear definition together with a simple example that explains what is a "callback hell" for someone who does not know JavaScript and node.js ?

When (in what kind of settings) does the "callback hell problem" occur?

Why does it occur?

Is "callback hell" always related to…

Some interesting things worth learning πŸ“—

Should i be using callbacks? πŸ˜•

Well, as long as you understand what you are working with, you are good to use it. But if any other incremental changes may have to be done to that function then you are better off with promises.

I still use callbacks sometimes especially when i need a function like setTimeout. But other than that i always use promises and/or Rxjs.

Why do i use promises or Rxjs instead of callbacks? πŸ’­

Well as you know callback functions are .... functions! that means they do not return a value themselves but will call a function at later point in time which returns a value.
But promises return value as soon as they are resolved or rejected.
Same way with Rxjs Observables, it returns an observable which we subscribe to and then will return a value when the asynchronous task finishes.

Note: An advantage of using Observables is that unlike promises we can emit multiple values over time using Observables, we can cancel if we choose to and can use with map, filter, reduce etc...with ease.

While there are many asynchronous tasks we can make use of promises in, I personally do a lot of API calls and that is where i use promises and Observables [For caching and stuff] where previously when i was just using ajax or jQuery with callbacks, it was a nightmare to chain multiple requests and merge them to return the result [Rxjs just makes it easier].

Let's see that with a simple example:

Using ajax and callback:


function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

Enter fullscreen mode Exit fullscreen mode

The above code, on success will run the function handleData which can have the logic you need.

Using promises:


const baseUrl = `https://placeholder.com/`;

function callPlaceholder(){
    return this.http.get(baseUrl).toPromise();
}

Enter fullscreen mode Exit fullscreen mode

And then use then() with callPlaceholder() as below:


callPlaceholder().then( res => {
        console.log(res);
    },
    error => {
        console.log(error);
    }
)

Enter fullscreen mode Exit fullscreen mode

So, yeah since we now have many ways to handle asynchronous requests, it's better to use them: [Especially for http requests]

βœ”οΈ XMLHTTPRequest.onreadystatechange()
βœ”οΈ jQuery methods
βœ”οΈ fetchApi
βœ”οΈ Axios
βœ”οΈ httpClients for respective frameworks & RxjsπŸ”₯

For more info visit this link

If you are curious about why javascript isn't multithreaded πŸ‘‡

Is it a deliberate design decision or a problem with our current day browsers which will be rectified in the coming versions?

Wrapping up

We now know:

βœ… what callback functions are
βœ… how to use them
βœ… why we use them
βœ… the concept behind why we might need them
βœ… and when to use them.

Hope this article has helped you! πŸ’β€β™‚οΈ

Stay tuned 🍿 for the final post in this series Generator functions.

Thank you!πŸ˜€

Top comments (2)

Collapse
 
chonerman profile image
Chace

Can you further break down why you'd use a Promise vs a Callback?

Collapse
 
bharathck profile image
G U BHARATH CHANDRA

Hey Chace, i have updated the post with why i use Promises and what it accomplishes. while it's not a complete guide, i guess you will get an idea.