Open In App

What is Callback Hell and how to avoid it in Node.js ?

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about Callback Hell and how can it be avoided. Callbacks Hell is the situation in which we have complex nested callbacks. As we have mentioned the term “Callback” so Before diving into Callback Hell details, let’s know a little about what Callback is. A Callback is a function that is called automatically when a particular task is completed. Basically, it allows the program to run other code until a certain task is not completed. This function allows you to perform a large number of I/O operations that can be handled by your OS without waiting for any I/O operation to finish which makes nodeJs highly scalable.

Syntax: 

const fs = require("fs");
fs.readFile("file_path", "utf8", function (err, data) {
    if (err) {
        // Handle the error  
    } else {
        // Process the file text given with data
    }
});

What is Callback Hell?

Callback hell in Node.js is the situation in which we have complex nested callbacks. In this, each callback takes arguments that have been obtained as a result of previous callbacks. In this manner, The code structure looks like a pyramid, which leads to less readability and difficulty in maintenance. Also, if there is an error in one function, then all other functions get affected.

Creating The Structure: 

Step 1: Create a text file input.txt with the following text:

Welcome to GFG.
Learn NodeJS with GeeksforGeeks

Step 2: Now, create a javascript file name main.js.

Project Structure: 

gfg

Example: This is a simple example of Callback Hell. We can see that in the code there are nested callbacks which are making it harder to understand the code. 

Javascript




const fs = require("fs");
const textFile = "input.txt";
fs.exists(textFile, function (exists) {
    if (exists) {
        fs.stat(textFile, function (err, res) {
            if (err) {
                throw err;
            }
            if (res.isFile()) {
                fs.readFile(textFile,
                    "utf-8", function (err, data) {
                        if (err) {
                            throw err;
                        }
                        console.log(data);
                    });
            }
        });
    }
});


Run the server: Now run the main.js to see the result with the following command:

node main.js

Output:

In this example, we have an fs module of nodeJS that provides the functionality of File I/O operations. With the help of the exists() function, we are able to test whether the given path exists or not in the file system. If it exists we have defined a function inside it.  Hence in this example, we are defining the function within another function that creates a callback hell problem for us as it is difficult to understand and read the code.

How can we avoid the “Callback Hell”?

Promise: With the help of Promises callback hell can be avoided. Promises in javascript are a way to handle asynchronous operations in Node.js. It allows us to return a value from an asynchronous function like a synchronous function. When we return something from an asynchronous method it returns a promise which can be used to consume the final value when it is available in the future with the help of the then() method or awaits inside of async functions. The syntax to create a promise is mentioned below.

Syntax:

const promise = new Promise(function (resolve, reject) {
    // code logic
});

Example: In this example, we are reading a textile named “input.txt” with the help of promises. Create a javascript file name main.js and write the following code:

Javascript




const fs = require('fs');
const fsPromises = require('fs').promises;
fs.promises.readFile("input.txt")
    .then(function (data) {
        console.log("" + data);
    })
    .catch(function (error) {
        console.log(error);
    })


Run the server: Now run the main.js to see the result with the following command:

node main.js

Output:

In this example, we have an fs module of nodeJS that provides the functionality of File I/O operations. Then we read the file with the help of the fs.promises.readfile method which returns a promise.

Async.js: Another way to avoid callback hell is, we have this npm module called Async. Async is helpful in managing asynchronous JavaScript. Some useful methods of Async are series, parallel, waterfall, etc. It works for browsers as well.

Installation:

npm i async

To avoid callback, We should avoid using more than two nested callback functions in a program as it will help in maintaining code readability.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads