The Callback Pattern: Node.js Conventions
Learn about Node.js conventions in the callback pattern.
We'll cover the following...
In Node.js, CPS APIs and callbacks follow a set of specific conventions. These conventions apply to the Node.js core API, but they’re also followed by the vast majority of the userland modules and applications. So, it’s very important that we understand them and make sure that we comply whenever we need to design an asynchronous API that makes use of callbacks.
The callback comes last
In all core Node.js functions, the standard convention is that when a function accepts a callback as input, this has to be passed as the last argument.
Let’s take the following Node.js core API as an example:
readFile(filename, [options], callback)
As we can see from the signature of the preceding function, the callback is always put in the last position, even in the presence of optional arguments. The reason for this convention is that the function call is more readable in case the callback is defined in place.
Any error always comes first
In CPS, errors are propagated like any other type of result, that is, using callbacks. In Node.js, any error produced by a CPS function is always passed as the first argument of the callback, and any actual result is passed starting from the second argument. ...