If your callback is in the form:
err => {
if (err) callback(err);
else callback();
}
or in the form:
(err, ...data) => {
if (err) callback(err);
else callback(null, ...data);
}
then just use
callback
instead of using either of them.
The following callback:
err => {
if (err) callback(err);
else callback();
}
can probably be shortened to just:
err => {callback(err)}
Because if err
is null or undefined, then callback(err)
would be equivalent to callback()
.
Actually you can use this pattern even when there are arguments that are passed to the callback. In other words, when all that your callback function does is to call the "super" callback, you can shorten it from:
(err, data) => {
if (err) callback(err);
else callback(null, data);
}
to:
(err, data) => {callback(err, data)}
which can be shortened to:
(...args) => {callback(...args)}
Realize that these two code snippets have equivalent functionality.
You can even put them into a callback generator function and simply run the callback generator with passing the "real callback" (the "super callback") as the argument:
function getCallback(superCallback) {
return (...args) => {superCallback(...args)}
}
and use it like:
getCallback(callback)
Actually, thinking about it, I think you don't even need the "callback generator" (that is, getCallback
). If I'm not wrong, you can just use:
callback
instead of:
(...args) => {callback(...args)}