Skip to content

Instantly share code, notes, and snippets.

@ugultopu
Last active December 28, 2020 19:12
Show Gist options
  • Save ugultopu/820d0453dfde6b1d20dc654af5f44fa4 to your computer and use it in GitHub Desktop.
Save ugultopu/820d0453dfde6b1d20dc654af5f44fa4 to your computer and use it in GitHub Desktop.

Summary

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.

Details

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)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment