a blog for those who code

Wednesday 7 October 2015

What are Error First Callbacks in Nodejs

In this post we will be discussing about Error-first callbacks in Node.js. Before discussing about Error-first callbacks, we should know what exactly is callback in Node.js. A callback is an asynchronous equivalent for a function which is being called when a given task is completed.

Node.js makes heavy use of callbacks, all the API's are written such as way that it supports callbacks. The advantage of using callback is that it makes Node.js highly scalable i.e. processing high number of request without waiting for any function to complete. A simple example of callback is as follows in which we are passing a function (callBackFunc) as an argument to another function.

var callBackFunc = function () {
  console.log('In am in callBackFunc');
callingFunction(argument, callBackFunc);

The "error-first" callback is nothing but a standard protocol for Node callbacks. The "error-first" callback has a simple rule that the first argument for the callback function should be an error object. If the error argument is null, then the operation was successful and if the error argument is not null, then an error has occurred.

Almost all Node.js code follows this style because without it developer has to spent a lot of time in maintaining different signature and styles for each and every callback.

Lets take an example of fs.readFile, in which the callback gets two arguments err and data.

fs.readFile('test.txt', function(err, data) {
  if(err) throw err;
  console.log(data); // data is the file content

As you can see in the above example the first argument of a callback function is Error object thus it is an "error-first" callback. If there is an error throw the error otherwise the reading operation is successful.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.