13 Followers
·
Follow

Nov 15th, 2016

Assuming there was no fatal error, should the first argument to an asynchronous callback be `undefined` or `null`?

Best practices for passing the first argument to an asynchronous callback

This is the short and sweet version. If you find it helpful, you might want to check out the entire gist.

In your implementation, if you always do one of the following, you’ll be good to go, and you’ll provide a better experience for the people using your thing:

1. Invoke callback with only err => new Error()

Some kind of fatal error occurred– something where I’d normally throw. Except that I’m an asynchronous function. So instead, I do this:

return cb(new Error('Something bad happened!'));

This is like doing throw new Error('Something bad happened!'); in a synchronous function.

2. Invoke callback with no arguments

Everything is AOK, and there’s no other data to send back:

return cb();

This is like doing return; in a synchronous function.

3. Invoke callback with err => undefined and yourResult

Everything is AOK, and there’s this result I want to send back:

return cb(undefined, yourResult);

This is like doing return yourResult; in a synchronous function.

Written by

We make Sails work and things work with Sails.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store