-
Notifications
You must be signed in to change notification settings - Fork 92
pdbtest: Improve Promise patterns #73
Description
Excellent article on the Blackberry Dev Blog. :) I took a look at your code, though, and I see a few places for improvement.
First, I think you might not be aware that you can improve your Promise patterns to avoid the "pyramid of doom" (i.e. code marching steadily to the right, until you are a dozen indentation levels deep).
For instance, this code is needlessly pyramid-y. (It's a common mistake folks make with Promises, though!) In general, what you don't want to do is this:
// BAD pyramid code
doSomething().then(function () {
doSomethingElse().then(function () {
doAnotherThing().then(function () {
// etc.
}).catch(function (err) {
// handle error
});
}).catch(function (err) {
// handle error
});
}).catch(function (err) {
// handle error
});Instead you can do:
// GOOD pyramid-less code!
doSomething().then(function () {
return doSomethingElse();
}).then(function () {
return doAnotherThing();
}).catch(function (err) {
// handle errors all in one place!
});Now let's say that you want to handle an error in a particular place. You can simply do:
doSomething().then(function () {
return doSomethingElse();
}).catch(function (err) {
// handle some very specific error
return anotherPromiseOrMaybeAValue();
}).then(function () {
return doAnotherThing();
}).catch(function (err) {
// handle errors all in one place!
});Also, a lot of your error handling seems to be caused by 409s and 404s, which you can now handle more elegantly with the pouchdb-upsert plugin. But it's good to get some promise practice in, so maybe you'll want to catch your own 409s and 404s using the pattern I described above. :)
Great work, looking forward to your next article!