Callbacks in Nodejs: A 2021’s Comprehensive Guide

In this tutorial, I am going to cover something of utmost importance: Callbacks in Nodejs.

Callbacks in Nodejs lay its foundation. When comparing a code for an operation with plain JavaScript, it might seem unnecessarily complicated. I will cover some examples down the post so you can have a better understanding.

But first, let us get our basics right.

What are Callbacks in Nodejs?

Before I jump to the definition and explanation of callbacks in Nodejs, I’d rather first explain the real difference between plain JavaScript and Nodejs in executing operations; and how Nodejs is better.

Comparing a JS Sync Operation with Node

Okay, so I found this great example from the official Nodejs.org docs.

When writing plain JS, in a synchronous program, your code would look something like this:

function processData () {
  var data = fetchData ();
  data += 1;
  return data;
}

Although the above code works just fine, there’s a drawback to it. If

fetchData()
function takes time, maybe because it is being streamed off the internet or the drive, this will cause all other operations to block, as we call it – meaning the ‘sitting still and waiting’ behavior entire data loads.

Let us take a look at Node’s version of this operation:

function processData (callback) {
  fetchData(function (err, data) {
    if (err) {
      console.log("An error has occurred. Abort everything!");
      return callback(err);
    }
    data += 1;
    callback(data);
  });
}

While this might seem complicated, this is way more useful for your application. Also, it isn’t as complicated as it seems when you begin to understand what’s happening and get your basics braced.

Now, Nodejs is an asynchronous framework of JavaScript. What does that mean? Simply put, Node doesn’t show the ‘sitting still and waiting’ behavior. Instead, it works on a non-blocking file I/O i.e., Input/Output architecture. This means Node doesn’t wait for other operations to load.

To achieve this, Node uses something called callbacks!

Now comes the question what are callbacks in Nodejs!

Explaining Callbacks in Nodejs

Callbacks in Nodejs are functions that are called after a given operation. They are more like asynchronous alternatives to a function in Nodejs. This prevents blocking any task or operation or allowing other code to run.

The “do this, once you’re done doing that” approach taken by callbacks in Nodejs, allows you to conduct as many I/O operations as your operating system supports.

All APIs in Nodejs are written in such a way that they support callbacks.

Synchronous & Asynchronous JavaScript

Although we discussed in bits the synchronous and asynchronous operations in JavaScript, it is time we learn about them in slight detail.

Synchronous JavaScript

Synchronous operations in JavaScript are referred to as operations that are executed one at a time. All other operations running simultaneously will be put on hold. They run one at a time because they are single-threaded.

The browser returns the result of the code as soon as possible once it is run.

Asynchronous JavaScript

Some operations in JavaScript require AJAX to complete as the response from particular operations is not immediate. It may take some time and it is not possible to jump to the next operation quickly.

This requires operations to wait for other operations to finish running in the background. Here is when asynchronous callbacks come into the picture.

AJAX enables many operations to be performed simultaneously. Click here to read more about Asynchronous Programming in Nodejs.

What is a Callback Hell?

Now that we understand what are synchronous and asynchronous JS, let us now take a look at a small concept of callback hell in Nodejs.

Callback hell is a code structure issue caused by the complex nesting of callbacks into callbacks! This is more like a disaster for any developer as it becomes difficult to read, debug and understand. If someone else were to read your code with callback hell in it, he/she is sure gonna curse you, not gonna lie!

Callback hell is created when a callback accepts an argument which is again a result of the previous callback! The code ends up looking a pyramid with tons of nested codes ending with a ton of these – })

If there’s an error in one of your callbacks, it will affect the entire set of callbacks linked to it.

Here’s a small example of a callback hell I picked from a one-page website just about callback hell:

fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

You can see references below to visit the website. Take a look at this code! Anyone’s for sure going to have a tough time understanding it! And, it really looks like a pyramid.

It is advised to use event queues and promises to escape from callback hell.

Conclusion

This article elucidates on callbacks in Nodejs and things related to it. Callbacks in Nodejs are of utmost as the frameworks make immense use of it. Callbacks are what make Nodejs apps highly scalable and responsive.

Noteworthy References

Aneesha S
Aneesha S
Articles: 172