DEV Community

Cover image for What is Callback Hell?
Ekaterine Mitagvaria
Ekaterine Mitagvaria

Posted on • Edited on

What is Callback Hell?

In programming, callback hell refers to an ineffective way of writing asynchronous code and overusing callbacks. It takes place when you nest functions and create too many levels of nesting. This makes it harder to control access to the specific function and it becomes harder to debug the issues.
Nesting means placing one function in another, placing the third function in the second, then the fourth in the third function, and so on. By placing the callback function in another callback, then again another callback in another callback, in more complex applications, callback logic might get too messy! This type of nesting visually looks like a pyramid which is why callback hell is also called a pyramid of doom. πŸ‘Ή

Before reading further, get familiar with the callbacks first.

Let’s remember what the callback function is in action while we prepare some Italian Moka coffee.

Buy some coffee before filling the boiler

Buy some coffee before filling the boiler

Fill the boiler before filling the funnel

Fill the boiler before filling the funnel

Fill the funnel before placing the pot on stove

Fill the funnel before placing the pot on stove

Place the pot on the stove before removing it

Place the pot on the stove before removing it

Remove the pot before pouring coffee

Remove the pot before pouring coffee

There you go, we made some coffee by using a callback function named nextAction in each of the functions. Each step will lead to the next, then to the next and so on - one action will not start until the previous one is done.

But what if I start preparing some salad where I have to go through 10x more steps? And what if I want to prepare soup? And maybe some more meals because I have many guests?

That’s why I will wrap all actions into one function and delegate this function task to my husband - so everything will be done by only him.

Callback hell

And here we got some callback hell where finalStep is nested inside startPreparing which is nested instead prepareFunnel which is nested inside prepareBoiler which is nested inside prepareMoka… Things can get even worse and imagine how hard it can be to debug this.

As a beginner, you might not stumble upon a callback hell anytime soon however do not fret! Once you do, as long as you know what it is you will be partly prepared. There are some ways to avoid this which I will explain later. For now, enjoy some coffee! β˜•οΈ

Top comments (4)

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Nice post, keep it on! 😁

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

Thank you so much πŸ‘€

Collapse
 
bunthorn01 profile image
αž”αŸŠαž»αž“αžαž“ - Bunthorn

thank

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

πŸ™ŒπŸ»