RaghavBang
Published in

RaghavBang

JavaScript Callback Hell😵😵

console.log("Callback hell")
func(val1) {
func(val2) {
func(val3) {
func(val4) {
consolo.log("This is called Callback hell")
}
}
}
}

To understand Callback hell, you must know that JavaScript is single threaded synchronous language. But with help of callback queue and event loop , JS provides the functionality to do asynchronous programming. Once the callstack is empty, event loop puts the callback function from callback queue into callstack.

Before going further lets understand few terminologies in JS.😎

Callback function: A callback is a function that is passed as an argument to another function.

Call Stack: It maintains the order of execution of execution context.

Callback queue: This is where our asynchronous code gets pushed to, and waits for the execution.

Event loop: It makes sure our asynchronous code runs after all the synchronous code is done execution. It keeps running continuously and checks the Callstack, if it don’t have any frames to execute then it checks Callback queue, if Callback queue has codes to execute then it pops the message from it to the Call Stack for the execution.

Let us take example of Sync and async Code:

Synchronous Code:

function f1() {
console.log("Welcome")
}
function f2() {
console.log("to")
}
function f3() {
console.log("Callback Hell")
}
// Invoke the functions
f1();
f2();
f3();
//Output will be:
//Welcome
//to
//Callback Hell

In above code the functions are called one by one. First, f1() goes into the callstack, executes, and pops out. Then f2() does the same, and finally f3(). After that, the callstack is empty, nothing else to execute. It is synchronous part of JavaScript.

Synchronous Callback Function:

function greeting(name) {
console.log(`Hi ${name}`)
}

function userInput(callback) {
const name = "David"
callback(name)
}

userInput(greeting)

The above example is a synchronous callback, as it is executed immediately.

“greeting” is callback function here.

Output of the code will be:

Hi David

Asynchronous Callback function Code:

function callback() {
console.log('I am callback');
}

function hello() {
console.log('Hello');
}

setTimeout(callback, 3000);
hello();

So, What do you think the output will be?

Will the JavaScript engine wait for 3 seconds to go to the call hello() function and output this:

I am callback
Hello

Or it will continue its execution without waiting for setTimeout function to execute. So, if you think , this is gonna happen, then you are right. This is how async code work.

The output will be

Hello
I am callback

The control flow of above async code is like this —

  1. The setTimeout function is called, passing an callback function that will be execute when timer ends in the future. (But only when the callstack is empty as setTimeout is executed in Web API)
  2. “Hello” is immediately output to the console.
  3. As now callstack is empty and once the timer of 3 seconds over, response comes back and our callback function is executed, “I am callback” is output to the console. (Event loop and callback queue are working in behind).

Here callback function is called to continue code execution after an asynchronous operation has completed these are called asynchronous callbacks.

Why do we need callback functions ?

Callbacks make sure that a function is not going to executed before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened.

Now coming to the real deal of callback hell 😅

We don’t do a single task in our code, we just make multiple calls to our backend (API ) and each of them depends on the previous call.

Callback hell is when you have too many nested callbacks

Too many people will feel brain freeze just by reading the above code. Now just imagine, having an application with hundreds of similar code blocks will cause even more trouble for the developer, even if they wrote it themselves.

In callback hell each function gets an argument which is another function that too is called with another parameter. Error handling becomes difficult in callback such code.

Thus to solve the issue of callback hell, Promise is used and has got so much attention. (In every interview you will be asked this question).

They provide a better way to do async operation using .then(), async and await. It also provides easy way to handle errors using .catch().

Promise is for another blog. I won’t cover it in this blog.😅

Conclusion

Callback function is not easy to maintain.

But do remember that callbacks functions are a fundamental and most important part of JavaScript. But now promises and async-await solves the problem of callback hell.

Note: Callback hell is also called as Pyramid of Doom!!

If you like this post and find it helpful you can give me claps 😍!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store