📌 Before understanding what callback hell is, make sure to get familiar with the callback first.
In programming, callback hell refers to an ineffective way of writing asynchronous code. 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, then placing the third function in the second, then the fourth in the third one, and so on. By placing callback in the callback and callback in the callback, with 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. 👹
Let’s remember what the callback function is in action while we prepare some Italian Moka coffee.
Buy some coffee before filling the boiler
Fill the boiler before filling the funnel
Fill the funnel before placing the pot on stove
Place the pot on the stove before removing it
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. So each step will lead to the next, then to the next and so on - one actions will not start until the previous one is done.
But what if I start preparing some salad where I have to go though 10x more steps? And what if I want to prepare soup as well? And maybe some more meals because of 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.
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… And things can get even worse sometimes!
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! ☕️
📌 Enjoyed the post? Please let me know in the comment down below!