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.

138 lines
2.9 KiB

4 years ago
  1. # p-retry [![Build Status](https://travis-ci.org/sindresorhus/p-retry.svg?branch=master)](https://travis-ci.org/sindresorhus/p-retry)
  2. > Retry a promise-returning or async function
  3. It does exponential backoff and supports custom retry strategies for failed operations.
  4. ## Install
  5. ```
  6. $ npm install p-retry
  7. ```
  8. ## Usage
  9. ```js
  10. const pRetry = require('p-retry');
  11. const fetch = require('node-fetch');
  12. const run = async () => {
  13. const response = await fetch('https://sindresorhus.com/unicorn');
  14. // Abort retrying if the resource doesn't exist
  15. if (response.status === 404) {
  16. throw new pRetry.AbortError(response.statusText);
  17. }
  18. return response.blob();
  19. };
  20. (async () => {
  21. console.log(await pRetry(run, {retries: 5}));
  22. })();
  23. ```
  24. With the `onFailedAttempt` option:
  25. ```js
  26. const run = async () => {
  27. const response = await fetch('https://sindresorhus.com/unicorn');
  28. if (response.status !== 200) {
  29. throw new Error(response.statusText);
  30. }
  31. return response.json();
  32. };
  33. (async () => {
  34. const result = await pRetry(run, {
  35. onFailedAttempt: error => {
  36. console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`);
  37. // 1st request => Attempt 1 failed. There are 4 retries left.
  38. // 2nd request => Attempt 2 failed. There are 3 retries left.
  39. // …
  40. },
  41. retries: 5
  42. });
  43. console.log(result);
  44. })();
  45. ```
  46. ## API
  47. ### pRetry(input, [options])
  48. Returns a `Promise` that is fulfilled when calling `input` returns a fulfilled promise. If calling `input` returns a rejected promise, `input` is called again until the max retries are reached, it then rejects with the last rejection reason.
  49. It doesn't retry on `TypeError` as that's a user error.
  50. #### input
  51. Type: `Function`
  52. Receives the number of attempts as the first argument and is expected to return a `Promise` or any value.
  53. #### options
  54. Type: `Object`
  55. Options are passed to the [`retry`](https://github.com/tim-kos/node-retry#retryoperationoptions) module.
  56. ##### onFailedAttempt(error)
  57. Type: `Function`
  58. Callback invoked on each retry. Receives the error thrown by `input` as the first argument with properties `attemptNumber` and `retriesLeft` which indicate the current attempt number and the number of attempts left, respectively.
  59. ### pRetry.AbortError(message|error)
  60. Abort retrying and reject the promise.
  61. ### message
  62. Type: `string`
  63. Error message.
  64. ### error
  65. Type: `Error`
  66. Custom error.
  67. ## Tip
  68. You can pass arguments to the function being retried by wrapping it in an inline arrow function:
  69. ```js
  70. const pRetry = require('p-retry');
  71. const run = async emoji => {
  72. // …
  73. };
  74. (async () => {
  75. // Without arguments
  76. await pRetry(run, {retries: 5});
  77. // With arguments
  78. await pRetry(() => run('🦄'), {retries: 5});
  79. })();
  80. ```
  81. ## Related
  82. - [p-timeout](https://github.com/sindresorhus/p-timeout) - Timeout a promise after a specified amount of time
  83. - [More…](https://github.com/sindresorhus/promise-fun)
  84. ## License
  85. MIT © [Sindre Sorhus](https://sindresorhus.com)