We (and the JS SO chat room) had a talk with @rlemon some days ago about his Lit
ID: 646116 • Letter: W
Question
We (and the JS SO chat room) had a talk with @rlemon some days ago about his Little-XHR library about error handling.
Basically, we wanted to decide which error handling pattern should be used:
Or:
One is more jQuery-like, while the other is more Node-like. Some say that the first pattern makes you think more about handling error. I think the opposite, since you may forget the other callback function, while the argument is always there on the second pattern.
Any opinion/advantage/drawback about both these patterns?
Explanation / Answer
The real important feature is style consistency so you can write code in the same style and you can make meta programming assumptions about how asynchronous situations are handled.
I personally prefer
(err, data) because it's a standard way of handling things. It allows for function composition.
For example after.map uses this pattern. So code like
after.map(["foo.js", "bar.js"], function (fileName, callback) {
fs.readFile(fileName, function (err, file) {
callback(err, file)
})
}, function (err, files) {
// handle files
})
can be simplified to
after.map(["foo.js", "bar.js", fs.readFile, function (err, files) {
// handle files
})
Another advantage is that you can pass in a callback as a last parameter
asyncOperation(options, function (err, data) {
// not nested inside an object literal
})
The callback last approach is a nice API familiarity approach.
A further advantage is that you can easily forget to set the error handler in your object literal, or set it to some kind of default error handler.
When your using (err, data) it reminds you to think about how to efficiently handle this err every time.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.