-
Notifications
You must be signed in to change notification settings - Fork 300
Description
IMO, callbacks should have the error passed first. This is the standard practice in node, and increasingly in browser javascript, it is the convention that Koding uses, and it has some tangible advantages.
must handle errors
It is far too easy to ignore errors.
k.tell('maybeFails', { seed: Math.random() }, (err, result) => {
doStuffWithResult(result); // whoops, I forgot to handle the error!
});Putting the error somewhere other than first makes the omission even easier still.
k.tell('maybeFails', { seed: Math.random() }, result => {
doStuffWithResult(result); // didn't even see/know about the error (it's the second parameter)
});variadic callback signatures
Compare this:
cb(arg1, arg2, arg3, err)With this:
cb(err, arg1, arg2, arg3)In coffeescript, you could write:
k.tell 'fetchThimgamijigs', 42, (err, rest...) -> ...or in the next edition of JavaScript:
k.tell('fetchThimgamijigs', 42, (err, ...rest) => { ... });In ES6, the rest parameter must be last (although it's allowed in any position in coffee-script). Having the error first is better style, and lends itself to language idioms.
consistent convention
When the error is always first, we can make convenient assumptions. For instance, without knowing the details of a particular operation, I can write code that assumes that if the the first parameter of a callback is not null, then an error occurred. I can then leverage this information—for instance, I can pipeline the errors away into a triage, and the code doing the pipelining does not need to know anything particular about the individual errors.
I'll leave it there for now, but I guess that there are probably other advantages. These are the major ones tho.