You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
2.6 KiB
Markdown

# es6-promise-try
A `Promise.try` shim for ES6 Promises.
`Promise.try` is an important tool for writing robust and readable code with Promises ([this article](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/) explains why), but ES6 Promises do not ([yet](https://github.com/ljharb/proposal-promise-try)) include this in their specification. This module provides an implementation of `Promise.try` for ES6 Promises that can be used stand-alone, without modifying `Promise`'s prototype.
The goal of this module is to be *functionally equivalent* to Bluebird's `Promise.try` implementation. If you find that it behaves differently in some way, please file a bug.
__This module requires ES6 Promises to be available in your environment.__ If you are targeting a platform that doesn't (always) provide ES6 Promises natively, you will need to use a polyfill like [`es6-promise`](https://www.npmjs.com/package/es6-promise).
## License
[WTFPL](http://www.wtfpl.net/txt/copying/) or [CC0](https://creativecommons.org/publicdomain/zero/1.0/), whichever you prefer. A donation and/or attribution are appreciated, but not required.
## Donate
Maintaining open-source projects takes a lot of time, and the more donations I receive, the more time I can dedicate to open-source. If this module is useful to you, consider [making a donation](http://cryto.net/~joepie91/donate.html)!
You can donate using Bitcoin, PayPal, Flattr, cash-in-mail, SEPA transfers, and pretty much anything else. Thank you!
## Contributing
Pull requests welcome. Please make sure your modifications are in line with the overall code style, and ensure that you're editing the files in `src/`, not those in `lib/`.
Build tool of choice is `gulp`; simply run `gulp` while developing, and it will watch for changes.
Be aware that by making a pull request, you agree to release your modifications under the licenses stated above.
## Usage
An example from [the article](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/):
```javascript
var promiseTry = require("es6-promise-try");
function getUsername(userId) {
return promiseTry(function() {
return database.users.get({id: userID});
}).then(function(user) {
return user.name;
});
}
```
## API
### promiseTry(func)
Immediately invokes `func` - in the same tick of the event loop - and wraps it to provide error-handling and Promises/A+ compatibility, as described in [the article](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/). Functionally equivalent to [Bluebird's `Promise.try`](http://bluebirdjs.com/docs/api/promise.try.html).