Error-first callback in node.js

September 19, 2017 superadmin 0

The “error-first” callback is nothing but a standard protocol for Node callbacks. Error-first callbacks are used to pass errors and data as well. The “error-first” callback has a simple rule that the first argument for the callback function should be an error object and it has to be checked to see if something went wrong. Additional arguments are used to pass data. fs.readFile(“./test.php”, function(err, data) { if (err) { // handle the error, the return is important here // so execution stops here return console.log(err) } // use the data object console.log(data) }) As you can see in the above [...]

What is Callback hell in Node.JS

September 19, 2017 superadmin 0

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”); } }, [...]