What is “callback hell” and how can it be avoided?

 Posted by Manicse on 10/27/2016 | Category: Node.js Interview questions | Views: 167 | Points: 40
Answer:

“Callback hell” refers to heavily nested callbacks that have become unwieldy or unreadable.

Example:
query("SELECT clientId FROM clients WHERE clientName='picanteverde';", 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){
console.log("success!!");
}else{
console.log("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){
console.log("success!!");
}else{
console.log("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 clientId FROM clients WHERE clientName='picanteverde';",handleClient);


| Alert Moderator 

Comments or Responses

Login to post response