Here's an example of how you can simplify the all() code using promises. Note that I changed the semantics slightly in one place - when you query a db with no docs, the promise is resolved with {} instead of undefined, which I think is less surprising.
Promises take a long time to grok, but there are a few things I can briefly tell you that helped me out with understanding them:
1) Inside of a promise's then(), you can do one of three things: return another Promise, return a non-Promise (which is the final object that gets resolved), or throw an error (which invokes the catch(), i.e. the reject handler).
2) new Promise(function (resolve, reject) {}) is a fine pattern, but since PouchDB returns promises anyway, you can avoid doing it explicitly.
3) We use "chai as promises" and "mocha as promised," which is awesome because it means you never have to explicitly call done() inside of your tests. :) Just return a promise and everything will be handled automatically. I fixed up one of the tests for you to demonstrate. This has the added benefit of converting synchronous exceptions (e.g. TypeErrors) to async promise rejections that get reported by Mocha.
Here's an example of how you can simplify the
all()
code using promises. Note that I changed the semantics slightly in one place - when you query a db with no docs, the promise is resolved with{}
instead ofundefined
, which I think is less surprising.Promises take a long time to grok, but there are a few things I can briefly tell you that helped me out with understanding them:
1) Inside of a promise's
then()
, you can do one of three things: return another Promise, return a non-Promise (which is the final object that gets resolved), or throw an error (which invokes thecatch()
, i.e. thereject
handler).2)
new Promise(function (resolve, reject) {})
is a fine pattern, but since PouchDB returns promises anyway, you can avoid doing it explicitly.3) We use "chai as promises" and "mocha as promised," which is awesome because it means you never have to explicitly call
done()
inside of your tests. :) Just return a promise and everything will be handled automatically. I fixed up one of the tests for you to demonstrate. This has the added benefit of converting synchronous exceptions (e.g. TypeErrors) to async promise rejections that get reported by Mocha.