Skip to content
This repository has been archived by the owner on May 7, 2023. It is now read-only.

Latest commit

 

History

History
67 lines (51 loc) · 1.97 KB

node-error-first-callback.md

File metadata and controls

67 lines (51 loc) · 1.97 KB

NodeJS often uses a callback pattern where if an error is encountered during execution, this error is passed as the first argument to the callback. What are the advantages of this pattern?

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)
})

Answer

Advantages include:

  • Not needing to process data if there is no need to even reference it
  • Having a consistent API leads to more adoption
  • Ability to easily adapt a callback pattern that will lead to more maintainable code

As you can see from below example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an Error object, which then becomes the callback's only parameter. The callback function allows a user to easily know whether or not an error occurred.

This practice is also called the Node.js error convention, and this kind of callback implementations are called error-first callbacks.

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)

/*
  { stack: [Getter/Setter],
    arguments: undefined,
    type: undefined,
    message: 'Value is not true!' }
  Value was true.
*/

Good to hear

  • This is just a convention. However, you should stick to it.
Additional links