userimage
Moe

What is callback hell and how can it be avoided in node.js

What is callback hell and how can it be avoided in node.js
userimage
"Callback hell" refers to heavily nested callbacks that have become unweildy or unreadable.

An example of heavily nested code is below:

query("SELECT id FROM User WHERE name='Test';", function(id){
  query("SELECT * FROM transactions WHERE clientId=" + id, function(transactions){
    transactions.each(function(transac){
      query("UPDATE transactions SET value = " + (transac.value*0.1) + " WHERE id=" + transac.id, function(error){
        if(!error){
          alert("success!!");
        }else{
          alert("error");
        }
      });
    });
  });
});


The primary method to fix callback hell is usually referred to as modularization. The callbacks are broken out into independent functions which can be called with some parameters. So the first level of improvement might be:

var logError = function(error){
    if(!error){
      alert("success!!");
    }else{
      alert("error");
    }
  },
  updateTransaction = function(t){
    query("UPDATE transactions SET value = " + (t.value*0.1) + " WHERE id=" + t.id, logError);
  },
  handleTransactions = function(transactions){
    transactions.each(updateTransaction);
  },
  handleClient = function(id){
    query("SELECT * FROM transactions WHERE clientId=" + id, handleTransactions);
  };

query("SELECT id FROM User WHERE name='Test';", handleClient);

Even though this code is much easier to read, and we created some functions that we can even reuse later, in some cases it may be appropriate to use a more robust solution in the form of promises. Promises allow additional desirable behavior such as error propagation and chaining. Node.js doesnÂ’t include much core support for promises, so one of the popular promise libraries should be used. One of the most popular is the Q promise library.
Answer is