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

58 lines
1.3 KiB

4 years ago
  1. # p-try [![Build Status](https://travis-ci.org/sindresorhus/p-try.svg?branch=master)](https://travis-ci.org/sindresorhus/p-try)
  2. > Start a promise chain
  3. [How is it useful?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/)
  4. ## Install
  5. ```
  6. $ npm install p-try
  7. ```
  8. ## Usage
  9. ```js
  10. const pTry = require('p-try');
  11. (async () => {
  12. try {
  13. const value = await pTry(() => {
  14. return synchronousFunctionThatMightThrow();
  15. });
  16. console.log(value);
  17. } catch (error) {
  18. console.error(error);
  19. }
  20. })();
  21. ```
  22. ## API
  23. ### pTry(fn, ...arguments)
  24. Returns a `Promise` resolved with the value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error.
  25. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.
  26. #### fn
  27. The function to run to start the promise chain.
  28. #### arguments
  29. Arguments to pass to `fn`.
  30. ## Related
  31. - [p-finally](https://github.com/sindresorhus/p-finally) - `Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome
  32. - [More…](https://github.com/sindresorhus/promise-fun)
  33. ## License
  34. MIT © [Sindre Sorhus](https://sindresorhus.com)