Callback Hell

Callback Hell, also known as Pyramid of Doom, is an anti-pattern seen in code of asynchronous programming.

It is a slang term used to describe and unwieldy number of nested “if” statements or functions.

If you are not expecting your application logic to get too complex, a few callbacks seem harmless. But once your project requirements start to swell, you will quickly find yourself piling layers of nested callbacks. Congrats! Welcome to Callback Hell.

Callback Hell Node Js – JavaScript Callback

A Callback is a function “A” that is passed to another function “B” as a parameter. The function “B” executes the code “A” at some point. The invocation of “A” can be immediate, as in a synchronous callback, or, it can occur later as in an asynchronous callback. It’s actually a simple concept that will be well understood with an example:

In the code we can see how to make a call to readFile and we pass it as a second parameter function (Callback Hell). In this case, readFile is an asynchronous operation and when it’s done with the operation of reading the file, it will execute the callback by passing the results of the operation to parameters.

The use of callbacks makes the code difficult to write and maintain. It also increases the difficulty of identifying the flow of the application, which is an obstacle when it comes to making debug, hence the famous name to this problem: Callback Hell.

Q: What’s worse than callback hell?

A: Not fixing it.

So it is definitely recommended to do it right from the get-go and avoid deeply-nested callbacks. My favourite solution for this will be the usage of the Promise object. I have been dealing with Node.js for my last few projects and Promise managed to keep my sanity in check. But if you are looking for something more edgy, you will love Generators. Another elegant approach to get rid call back hell, is to use async.waterfall. I will touch more in depth about all the approaches below.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article