What is Callback Hell?

callbacks-callback-hell-promise

JavaScript programmers are talking a lot about callback hell. Callback hell is a concept that affects a JavaScript developer when he tries to perform various callbacks function one after the other. Some persons call it the pyramid of doom.

Using callbacks causes the program difficult to write and maintain. It also increases the problems of identifying the order flow, which is an obstacle when debugging, hence the famous name for this issue: Callback Hell.

For Example:

In the above code, there is three operation addition, Subtract and multiplication. Which is using a callback function to perform the task. But you can see the code, here I am using Subtract callback function under addition function and multiplication callback function under subtract function. The Above structure is known as the pyramid of doom as well as callback hell.

Difference Between Callback and Promise

Techniques for avoiding callback hell

Handling callbacks hell using promises

Promises are an option to callbacks when interacting with asynchronous code. Promises return the result value or an exception to a mistake. The heart of the promises is the.then() function, which waits for returning the promise object. The.then() function requires two optional functions as arguments and only one will ever be called depending on the state of the promise. The first method is called when the promise is fulfilled. When the promise is rejected, the second function is called.

Promises can be chained inside or outside the handler.then() function. Chaining promises outside the handle are very clean and simple to read, but if we want to use some parameters in our next handler that are accessible in the previous handler’s scope, we may have to chain promises inside the handler.

Learn More about : Callback vs Promise

Conclusion:

Getting rid of Callback Hell is not easy if you don’t follow correct coding rules and carry self-audits to your own codes. By using techniques above, however, it can be avoided.

Related posts