Daniel
Daniel

Reputation: 35684

When should an error-first callback be used?

There are two common ways of defining a function callback handlers:

passing individual success and fail callback functions

function doAsynchCall(on_success,on_fail){
    //do stuff
    if(condition === true){
        on_success(data);
    }
    else
    {
        on_fail(error);
    }
}

or handling the success/fail response within the same callback (error-first, err-back, node-style)

function doAsynchCall(callback){
    //do stuff
    if(condition === true){
        callback(null,data);
    }
    else
    {
        callback(error,null);
    }
}

I've noticed that both versions get used, both work, and there is some degree of personal choice involved, but I'm certain there are some facts to support why one version may be preferred over other, or cases where the use warrants one over the other.

TL;DR;

What are the benefits and disadvantages of using a error-first callback?

Upvotes: 4

Views: 717

Answers (1)

nem035
nem035

Reputation: 35481

From the perspective of the user of the function, I would argue that the first way is better. Reason is that it leaves less work for the him/her and also allows for cleaner code. The user doesn't have to worry about determining if an error happened, he knows that his error handler will be called in case of an error.

// Clean, modularized logic

function success() {
  // handle success
}

function error() {
  // handle error
}

doAsynchCall(success, error);

In the second way, by simply calling the function, the user doesn't know if an error has happened and essentially has to do the work of the if statement again to determine where to proceed.

// does essentially the same stuff as doAsynchCall
function handler(error, data) {
  if (error !== null) {
    // handle error
  } else {
    // handle success
  }
}

doAsynchCall(handler):

However, the situation is basically inverted from the perspective of the function designer. For him/her, it is easier to always pass the error as the first argument and and let the user determine how to handle and if to branch on an error.

function doAsynchCall(callback) {
    let data = getDataOrAnErrorHappens(); 
    callback(error, data);
}

Upvotes: 4

Related Questions