1. Overview

In this article, we will learn what are the function callback in Nodejs/Angular/JavaScript? How it is useful? What are the drawbacks of callback? and what we can use instead of callback? We will learn here NodeJs function callback with an example, advantages and limitation of function callback.

2. Function callback In Nodejs

2.1 What is a function Callback?

A callback is a function called at the completion of a given task; this prevents any blocking and allows other code to be run in the meantime. So, a callback is an asynchronous equivalent for a function. Instead of immediately returning a result like most functions, functions that use callback take some time to produce a result. All APIs of Node are written in a way to supports callback.

2.2 Why function Callback?

Before we learn callback, we need to understand why we need it? We need it because of Node’s asynchronous nature(non-blocking).

Now, the question arises what is Asynchronous programming?

In simple words, while your code waits for something to be done (like an API call or download something). it can do something else. i.e. your code doesn’t get blocked because of other lengthy processes.

2.3 When to use function Callback?

The callback is generally used when the function needs to perform events before the callback is executed. Usually, callback is only used when doing I/O, e.g. downloading things, reading files, talking to databases, etc.

3. Examples of function callback In Nodejs

The below code works fine in other development environments.

function getData() {
    var data = fetchDataFromServer();
    console.log("data fetched...");
    return data;
}

However, if fetchDataFromServer takes a long time to load the data, then the above code causes the whole program to block(waiting – until it loads the data). Because it executes the program from top to bottom. First, it will fetch data from the server, then it will print data fetched...

let’s see, what happens when we use NodeJs callback.

3.1 Without function callback

function getData() {
    let data = fetchData();
    console.log("data ", data);
    console.log("End of the Code...");
}

function fetchData() {
    let data;
    setTimeout(function() {
        data = 10;
        console.log("data received...");
        return data;
    }, 3000);
}
getData();

 Output :

data undefined
End of the Code...
data received...

Boom…! you will get data undefined here, why? the reason is the asynchronous nature of NodeJs. It won’t wait for the response of fetchData() and it will print consoles. In this scenario, callback come into the picture.

In the callback, we pass the callback function in the argument of the parent function. The callback function will be called after completion of the parent function.

3.2 With callback

In the case of callback, the function will be called after the execution of checkString().

function getData(data) {
    checkString(data, function(err, res) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log("data ", res);
        }
        console.log("End of the Code...");
    });
}

function checkString(data, next) {
    setTimeout(function() {
        if (typeof data !== 'string') {
            next(new Error("Data must be string"));
        } else {
            console.log("data received...");
            next(null, data);
        }
    }, 3000);
}
getData("hello");

Above code checks data passed in argument is String or not. If it gets String as an argument, code executes normally.

Output :

data received...
data hello
End of the Code...

 

What if we pass no string arguments in function? It should throw an error. right? and we must handle errors in our code. Callback handles these errors too. Let’s take a look at it.

3.3 Error handling

The first argument of the callback is for an error object. If an error occurred, it will be returned by the first err argument. If no error occurred, err will be set to null.

The second argument of the callback is for successful response data. and any successful data will be returned in the second argument.

function getData(data) {
    checkString(data, function(err, res) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log("data ", res);
        }
        console.log("End of the Code...");
    });
}

function checkString(data, next) {
    setTimeout(function() {
        if (typeof data !== 'string') {
            next(new Error("Data must be string"));
        } else {
            console.log("data received...")
            next(null, data);
        }
    }, 3000);
}
getData(10);

 Output :

Error: Data must be string

4. Callback Hell

You might hear this word, Callback Hell.

What is Callback Hell?

It is a JavaScript anti-pattern caused by deeply nesting asynchronous functions. It consists of multiple nested callbacks which makes code hard to read and debug. Look at below code,

fs.readFile(filePath1, (err, data1) => {
  if (err) throw err
  fs.readFile(filePath2, (err, data2) => {
    if (err) throw err
    fs.readFile(filePath3, (err, data3) => {
      if (err) throw err
      fs.readFile(filePath4, (err, data4) => {
        if (err) throw err
        fs.readFile(filePath5, (err, data5) => {
          if (err) throw err
          console.log(
            concatFiles(data1, data2, data3, data4, data5)
          )
        })
      })
    })
  })
});

It is not the way you want your code to look alike. This Problem of Nodejs known as Callback Hell and it is a major drawback of callback.

There are many ways to fix callback hell, like do not nest functions, modularize code, handle every error, etc.

5. Drawbacks & Alternatives of Callback

5.1 Drawbacks

  • Error handling in complex asynchronous code is difficult.
  • Callback hell.
  • Raw callback sacrifice the control flow.

5.2 Alternatives

  • Promises
  • Async/Await

6. Conclusion

In conclusion, In this article, we have learned the basic concepts of callback in Nodejs, like what is callback? when we should use callback Nodejs? How to handle errors in the callback Nodejs? what is callback hell In Nodejs? We have also seen the cons and alternatives of callback in Nodejs. However, All the concepts are also applicable in javascript. As these are the basic concepts.

7. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *