Re:What's so great about JavaScript Promises?
by thedufer on Tuesday January 29, 2013 @05:27PM
(#5136791)
> With normal callback style error handling, you have to put "if (err) return cb(err)" after each async call. It's crazy.
Or use a sane async library. As far as I can tell, something like https://github.com/caolan/async gives you a strict superset of Promise features, unless you're for some reason tied to how code with promises looks.
Re:What's so great about JavaScript Promises?
by MatthewPhillips on Tuesday January 29, 2013 @02:05PM
(#5135622)
You can wrap your callback functions and handle errors all in one spot. Example:
var slice = Array.prototype.slice;
function errHandler(callback) {
return function(err) {
if(err) {
// Error handling code here.
} else {
callback(slice.call(arguments, 1));
}
};
}
Re:What's so great about JavaScript Promises?
by embwbam on Tuesday January 29, 2013 @03:11PM
(#5135965)
I've tried stuff like this before, but it clutters your code pretty bad anyway, doesn't it? You have to do something like this:
function myAsyncThing(cb) {
var handleErrors = errHandler(cb)
doSomethingElse(handleErrors(function(data) {
// repeat. use handleErrors at each callback.
}))
}
Am I missing something? Can you get it cleaner than that?
Re:What's so great about JavaScript Promises?
by MatthewPhillips on Tuesday January 29, 2013 @03:45PM
(#5136139)
That depends, if you're using doSomethingElse a lot I'd just go ahead and wrap that as well, if you're using it once it's no big deal.
doSomethingElse(errHandler(function(real, results) {
// foo
}));
If you're using Node you should be writing small(ish) modules anyways, so it doesn't lead to much code blote and its advantageous to consolidate your error handling in one or 2 spots.
With promises, you can attach an error handler once. If you think of errors as only unexpected conditions, you can have a single error handler for each set of operations and not have to worry about checking at each step.