Open In App

What is callback hell in Node.js ?

To know what is callback hell, we have to start with Synchronous and Asynchronous Javascript. 

What is Synchronous Javascript? In Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded. So, all other processes are put on hold while an operation is executed. 



What is Asynchronous Javascript?

What is a callback?



What is callback hell? 

This is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected. 

Example: This is an example of typical callback hell. 




app.get("/details", function (req, res) {
    const name = req.query.name;
    console.log(name);
 
    Scopus.find({ name: name },
        { '_id': 0, 'authorId': 1 },
        function (err, result) {
            if (err) { }
            else {
                let searchResult = result[0]["authorId"];
                console.log(searchResult);
                let options = {
                    url: "https://api.elsevier.com/content/author/author_id/"
                        + searchResult + "?apiKey",
                    headers: { 'Accept': 'application/json' }
                };
                request(options, function (error, response, body) {
                    if (error) {
 
                        // Print the error if one occurred
                        console.error('error in Authors :', error);
 
                        // Print the response status code if a response was received
                        console.log('statusCode:', response && response.statusCode);
                        res.send("error")
                    }
                    else if (!error) {
                        let jsonObj = JSON.parse(body);
                        if (jsonObj['author-retrieval-response'] == undefined) {
                            res.send("No details");
                        }
                        else {
                            let reqData = jsonObj['author-retrieval-response'][0];
                            let authprofile = reqData["author-profile"]
                            let names = authprofile["preferred-name"]["indexed-name"]
                            console.log(names);
                            let citation = reqData["coredata"]["citation-count"];
                            let query = { authorId: searchResult };
 
                            Scopus.findOneAndUpdate(query, {
                                name: names,
                                citationCount: citation
                            }, function (err, doc, res) {
                                if (err) {
                                    console.log("error");
                                }
                                else {
                                    console.log("success");
                                }
                            })
                            res.render("details", { data: reqData });
                        }
                    }
                });
            }
        })
});

You can notice the nested callbacks look like a pyramid which makes it difficult to understand.

 How to escape from a callback hell?


Article Tags :