What is Callback hell in Node.JS

Callback hell “refers to heavily nested callbacks that have become unreadable. To fix this we can break callbacks into independent functions that is referred as modularization.

An Example of heavily nested code is below:

query("SELECT userId FROM userss WHERE userName='jhon';", function(id){
  query("SELECT * FROM articles WHERE articleId=" + id, function(articles){
    articles.each(function(article){
      query("UPDATE articles SET status = '0' WHERE id=" + article.id, function(error){
        if(!error){
          console.log("success!!");
        }else{
          console.log("error");
        }
      });
    });
  });
});

To fix this, the above callbacks are broken out into independent functions which can be called with some parameters.

  var logError = function(error){
    if(!error){
      console.log("success!!");
    }else{
      console.log("error");
    }
  },
  updateArticle = function(a){
    query("UPDATE articles SET value = '0' WHERE id=" + a.id, logError);
  },
  articlesList = function(articles){
    articles.each(updateArticle);
  },
  usersList = function(id){
    query("SELECT * FROM articles WHERE clientId=" + id, articlesList);
  };

  query("SELECT userId FROM users WHERE userName='jhon';", usersList);

This code is much easier to read and we created some functions that we can even reuse later.

Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Share On Pinterest

Be the first to comment

Leave a Reply

Your email address will not be published.

*


*