Loading, please wait...

Nested Callbacks /Callback hell

When one callback is declared inside another callback this is called the nested callback.

A condition where the code becomes hard to understand or debug, due to the multiple nested callbacks, called callback hell.

How to Avoid Callback Hell?

There are multiple ways for avoiding Callback hell

  1. Modularize by code:

Normal code:

The callback function is a closure and can only be accessed inside the function. In this case, you can create a separate function by providing some name and pass that function as a callback as shown in the example.             

Modularize code

The only drawback with this procedure is you need to create lot of function as code grows

  1. Use Generator Generators provides you the ability to convert the asynchronous code to synchronous one.

Above code is asynchronous code so console.log() will execute prior to readFile().

In order to avoid putting our console.log() inside the callback closure, we can use generators to convert the asynchronous nature of readFile() into a synchronous one. As shown in given below code

Try to execute this code, you will see the content of file first and then console.log().

  1. Promise Approach:

Promise represents the result of the asynchronous function.it avoids chaining of the callback in node.js you can use Q or Bluebird module to avail the features of promise.

// Callback approach

// Promise approach

// Promise approach with chaining