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);
}
}
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){
...
});
});
});
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
})
}
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();
}
And then use then()
with callPlaceholder() as below:
callPlaceholder().then( res => {
console.log(res);
},
error => {
console.log(error);
}
)
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)
Can you further break down why you'd use a Promise vs a Callback?
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.