" Callback Hell or Pyramid of Doom "

" Callback Hell or Pyramid of Doom "

Callbacks:

I assume you know what callbacks are if you’re reading this blog. If you don’t, please read this blog for an introduction to callbacks before continuing. There, we talk about what callbacks are and why you use them in JavaScript.

What is " Callback Hell " or we can say " Pyramid of Doom "?

  • When there is a callback function in other callback function as an argument which again is in another callback and so on is called " Callback Hell " or " Pyramid of Doom ".
  • It is basically like a nested Callback function.
  • This makes the code more complex and deeper which results in difficulty in understanding and managing the code.
  • This is how a callback hell looks like:
  • The ' Pyramid ' of these calls grows towards the right with every asynchronous action. Soon it spirals out of control, thus this ways o coding is not that comfortable.
  • An example o callback hell:

Output:

Solutions to Callback Hell :

There are four solutions to callback hell:

  1. Write Comments:
  • In this writing comments or each and every step makes it easy to understand the flow of the code and also the program itself.
  • Now when you see the callback hell, you get an understanding of why it has to be written this way.
  1. Split functions into smaller functions:
  • As we can see in the callback hell condition there are many callback functions present we can further divide them into different functions to identify them, differentiate and understand them.
  1. Use Promises:
  • I’m going to assume you know what promises are. If you don’t, please read this blog.
  • Promises makes callback hell much easier to understand and manage.
  • The challenge is to convert the callback function into a promise.
    • Converting callback functions into promises:
        • First step is to create a new promise for each callback.
        • Resolve the promise or reject it with respect to the success of the callback function.
  1. Use Async/ await:
  • Two things are important for using this solution to avoid callback hell:
    1. How to convert a callback function into a promise.(This is explained in the above solution)
    2. How to use asynchronous functions.
  • With the help of asynchronous function we can write the main program as if it is synchronous again.

Read more