So the general convention for callback functions in Node.js is to "reserve" the first parameter for an error (if one exists). For example:
callSomeBlockingFcn( function callbackWhenDone(err, result) {
if( err ) ...
});
If you need to return more than one error--say multiple data validation errors, for example--is it considered poor form to pass an array of error objects? Example:
var callSomeBlockingFcn = function(callback) {
// multiple errors to report back...
callback( [ err1, err2, ...] );
}
Or is it preferable to avoid arrays and return a single object with a property referencing an array (if necessary)? Example:
var callSomeBlockingFcn = function(callback) {
// multiple errors to report back...
callback( { errors: [ err1, err2, ...] } );
}
Error-first callback in Node. js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This error object is returned by the first argument whenever any error occurs during the execution of the function.
As long as the callback code is purely sync than no two functions can execute parallel.
There are two most commonly used methods for chaining functions provided by the async module: parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired.
3 years later:
Anyone that puts an array in a callback will make me mad.
The correct solution is to return an error
as the first argument. If you want to return multiple errors you are probably using errors for non-exceptional cases.
In which case it should go in the "value" slot of the callback, i.e. the second argument. The first argument is for a single, unexpected operational error.
If you have multiple unexpected operational errors (unlikely) you can do something like this MultiError
Original:
I think there's nothing wrong with returning an array of errors.
Although you could return a new custom ValidationError
which has a property "messages"
which is an array.
a)
function validateX(x, cb) {
...
if (errorMessages) {
return cb(errorMessages);
}
}
b)
function ValidationError(msgs) {
this.messages = msgs;
}
function validateX(x, cb) {
...
if (errorMessages) {
return cb(new ValidationError(errorMessages));
}
}
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