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?
'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.
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.
fs. readFile(file, ErrorFirstCallback);
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With