Skip to main content

Node.js Callbacks

·272 words·2 mins
Table of Contents
Node.js - This article is part of a series.
Part : This Article

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.

Callback
#

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
    console.log(err)
    return
  }

  //no errors, process data
  console.log(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.

Node.js - This article is part of a series.
Part : This Article