Skip to content
This repository has been archived by the owner on Sep 4, 2019. It is now read-only.

pdbtest: Improve Promise patterns #73

Open
nolanlawson opened this issue May 7, 2015 · 2 comments
Open

pdbtest: Improve Promise patterns #73

nolanlawson opened this issue May 7, 2015 · 2 comments

Comments

@nolanlawson
Copy link

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!

@nolanlawson
Copy link
Author

Oh yeah, and the PouchDB guide to async code may help you out here, and the video in that article is a must-watch! :)

@timwindsor
Copy link
Contributor

Thanks Nolan - I'm not very familiar with the Promise pattern, and I don't think the student who wrote this is either. I really like the improvements to the code though, so I'm going to learn more and see if I can apply it, both here and elsewhere. Particularly I want see how APIs are written to work that way so we can apply it to our Cordova plugins where it makes sense to do so.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants