1.

What is call back and call back hell in Node.js?

Answer»

A callback function is called at the end of a SPECIFIC task or simply when another function has finished executing. Callback functions are used exclusively to support the ASYNCHRONOUS feature or non-blocking feature of Node.js. In the asynchronous programming with Node.js, servers don’t wait for any action like API call to complete to start a new API call.

For eg

Let’s  read a FILE say “input.txt” and print its output in the console.The synchronous or blocking code for the above requirement is shown below:

var fs = require("fs"); var data = fs.readFileSync('input.txt');  // execution stops and waits for the read to finish console.log(data.toString()); console.log("Program Ended");  Let’s rephrase the code with the callback function. var fs = require("fs"); fs.readFile('input.txt', function (err, data) {    if (err) return console.error(err);    console.log(data.toString()); }); console.log("Program Ended");

Here program does not wait for reading the file to complete but proceeds to print "Program Ended".If an error occurs during the read function readFile(), err object will contain the corresponding error and if the read is successful data object will contain the contents of the file. readFile() passes err and data object to the callback function after the read operation is complete, which finally prints the content.

Pyramid of Doom or Callback HELL happens when the node.js programs are very complex in nature and having HEAVILY nested callback functions. The name is attained by the pattern caused by nested callbacks which are unreadable.

For eg

Let’s assume that we have 3 different asynchronous tasks and each one depends on the previous result causing a mess in our code.

asyncFuncA(function(x){            asyncFuncB(x, function(y){                  asyncFuncC(y, function(z){                      ...                 });             });       });

Callback hell could be avoided by the following methods :

  • Handling all errors immediately
  • Splitting the callbacks into smaller and independent functions
  • Declaring callback functions beforehand.
  • Libraries like Async.js adds a layer of functions on top of your code reducing the complexity of nested callbacks.
  • Usage of Promises where async code could be written that handles errors due by the usage of try/catch-style error handling.


Discussion

No Comment Found