FOLASAYO SAMUEL OLAYEMI
SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

What benefits does this pattern offer in NodeJS?

FOLASAYO SAMUEL OLAYEMI's photo
FOLASAYO SAMUEL OLAYEMI
·Oct 15, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

NodeJS frequently employs a callback pattern where, in the event of an error, the callback receives the error as the first argument. What benefits does this pattern offer?

Code Sample:

fs.readFile(filePath, function(err, data) {
  if (err) {
    // handle the error, the return is important here
    // so execution stops here
    return console.log(err)
  }
  // use the data object
  console.log(data)
})

These are the benefits or advantages:

  • If there is no need to even reference the data, there is no need to process it.

  • A consistent API encourages more adoption.

  • A callback approach that is simple to modify and will result in better maintainable code.

The callback is called with null as its first argument if there is no error, as you can see from the sample below. The lone parameter for the callback becomes an Error object in the event of an error, though. The callback function makes it simple for a user to determine whether an error has occurred.

These callback implementations are known as error-first callbacks, and this technique is also known as the Node.js error convention.

var isTrue = function(value, callback) {
  if (value === true) {
    callback(null, "Value was true.")
  } else {
    callback(new Error("Value is not true!"))
  }
}

var callback = function(error, retval) {
  if (error) {
    console.log(error)
    return
  }
  console.log(retval)
}

isTrue(false, callback)
isTrue(true, callback)

Note: This is merely a custom. But you should adhere to it.

Thanks for reading...

Happy Coding!

Did you find this article valuable?

Support FOLASAYO SAMUEL OLAYEMI by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this