Error First Callbacks in Node JS

Callbacks are a systemic part of a Node.js application. A non-blocking well-balanced flow of controlled asynchronous modules is made possible by properly implemented callbacks. But what is “properly implemented”? Creating code that will scale with your projects means using a reliable protocol that is a well-known standard.

The “error-first” callback (also known as an “error-back”, “errback”, or “node-style callback”) was introduced to solve this problem and has since become the standard for Node.js callbacks.” — TheNodeWay

Having a dependable pattern when it comes to callbacks is important. This is because node uses asynchronous code heavily. The asynchronous code gets confusing really fast. It would be a heavy burden to bear for developers to be stuck maintaining varied styles from one module to the next.

“While every use-case has different requirements and responses, the error-first pattern can accommodate them all.” — TheNodeWay

The pattern is very simple. The first parameter of a callback is “reserved” for a possible error object. The second parameter is for successful response data. If there is no error then the error parameter will be null.
This means that successfully returned data is expected to be in the second argument.

Here is an example of what it may look like:

Notice that the first argument is the error object and can be checked. If there is an error, it is then handled. If there is no error, subsequent successful data arguments can then be processed.

Leave a Reply

Your email address will not be published. Required fields are marked *