Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the more correct position for the error argument in a javascript callback?

I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

  • Should the callback's error argument be first or last?
  • Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}

or this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}

or this:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

like image 408
Joseph Avatar asked May 17 '11 03:05

Joseph


People also ask

How do you handle errors in callback?

If an error-handling callback function has been specified in the application and if the value of the error parameter is NULL, the error parameter is passed to the specified callback function, and the operation that encountered the error condition returns a value of DW_DLV_ERROR.

Which is the correct syntax for error first callback?

fs. readFile(file, ErrorFirstCallback);

How do you pass an argument in a callback function?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.


1 Answers

You could specify two callbacks, one for success and one for error, and both encapsulated in a single "callbacks" argument. This is how many Javascript libraries handle your requirement.

var fooFn = function(bar, callbacks) {
  callbacks = callbacks || {}; //make callbacks argument optional
  ...
  if (error) {
    if (callbacks.error) {
      callbacks.error('troz not found'); //pass the error message as a string
    }
  } else if (callbacks.success) {
    callbacks.success(result);
  }
}

The success and error functions are optional. To specify both, call it like this:

fooFn("some bar", {
  success: function(result) {
    //success :-)
  },
  error: function(errorMsg) {
    //error :-(
  }
});

You can also do this:

fooFn("some other bar");

If you like, you can expand the callbacks object to support other scenarios, like "complete".

like image 126
Roy Tinker Avatar answered Oct 28 '22 07:10

Roy Tinker