Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add promised land function to easily promisify all cradle objects #316

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,28 @@ You can also get the current revisions limit
});
```

Modern async APIs
---

If you prefer to use modern async Javascript with `Promise`s or `async/await`, you can use the new handy `promised-land` helper method as follows:

```js
const cradle = require('cradle');
const client = // configure client
const db = // configure db from client

const P = require('bluebird')
const promisedLand = require('cradle/promised-land');
const promised = promisedLand(P.promisifyAll, {cradle, client, db});
```

Note that you can pass in whatever method you prefer to wrap all Object functions in promises. Here we use the `promisifyAll` method from the [bluebird](https://github.com/petkaantonov/bluebird) promise library.

You can now use the following promised enabled APIs as you see fit, even with `async/await` :)

- `promised.db`
- `promised.client`
- `promised.cradle`

### fetching a document _(GET)_ ###

Expand Down
14 changes: 14 additions & 0 deletions lib/cradle/promised-land.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

function promisify(options, key) {
let obj = options[key];
return obj ? promisifyAll(obj) : undefined;
}

module.exports = function(promisifyAll, options) {
['cradle', 'client', 'db'].reduce(function(key, result) {
result[key] = promisify(options, key);
return result
}, {})
}