Node.js Callbacks

When starting out with Node.js, I had a good grasp on the basics of JavaScript. But one thing that got me stumped was asynchronous programming with the help of callbacks. We will take a look at these concepts in this post.


A callback is a function that is passed to another function as a value, that gets executed when an event occurs. This is possible in JavaScript, because it treats functions as first class citizens. First Class Functions in a programming language is the ability of a function to behave like normal variables, like being able to be passed to other functions as a variable, assign to another variable, etc. The function to which a function is called a Higher Order Function.

A common way JavaScript uses callbacks is like as follows,

window.addEventListener('load', () => {
    //window loaded
    //do what you want  

So, we have a function that will get called when the event is triggered. But what to go when an error happens in the function?

One very common strategy is to use what Node.js adopted: the first parameter in any callback function is the error object: error-first callbacks

fs.readFile('/file.json', (err, data) => {
  if (err) {
    //handle error

  //no errors, process data

This would work great in simple cases, where there is one callback. But what if the callback function has another callback. This results in nested callbacks. This is bad for a number of reasons. First of all its confusing and difficult to maintain.

We will look further at the 2 different ways callbacks can be used in a future post.