{"name":"p-retry","version":"7.0.0","keywords":["promise","retry","retries","operation","failed","rejected","try","exponential","backoff","attempt","async","await","promises","concurrently","concurrency","parallel","bluebird"],"author":{"url":"https://sindresorhus.com","name":"Sindre Sorhus","email":"sindresorhus@gmail.com"},"license":"MIT","_id":"p-retry@7.0.0","maintainers":[{"name":"sindresorhus","email":"sindresorhus@gmail.com"}],"homepage":"https://github.com/sindresorhus/p-retry#readme","bugs":{"url":"https://github.com/sindresorhus/p-retry/issues"},"xo":{"rules":{"no-await-in-loop":"off"}},"dist":{"shasum":"38dbee20149d94680fe0a022405839d995f95e7b","tarball":"http://registry-npm.ywwl.com/p-retry/download/p-retry-7.0.0.tgz","fileCount":5,"integrity":"sha512-3BgO9rjULJYyr0Y0pcsG7FZ+7JB/hfOODO8kx9ppumiO5jprUF92WK/Y7Q0xppZtq4VhTcPiVq7qWLQfIV5aKQ==","signatures":[{"sig":"MEUCICzp2L9+VrWFqg3Iqc5Vb+MFuSwi64x/FOt6tdD4O7hUAiEAs9BjB4O5NjMUzgXDzdD9Jqx70f38wbz92kdG4VTBeM4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":19964,"size":5940,"noattachment":false,"key":"/p-retry/-/p-retry-7.0.0.tgz"},"type":"module","types":"./index.d.ts","engines":{"node":">=20"},"exports":{"types":"./index.d.ts","default":"./index.js"},"funding":"https://github.com/sponsors/sindresorhus","gitHead":"e11ca9c9c4a8032182403871593a67a49e948568","scripts":{"test":"xo && ava && tsd"},"_npmUser":{"name":"sindresorhus","email":"sindresorhus@gmail.com"},"repository":{"url":"git+https://github.com/sindresorhus/p-retry.git","type":"git"},"_npmVersion":"10.9.2","description":"Retry a promise-returning or async function","directories":{},"sideEffects":false,"_nodeVersion":"20.19.1","dependencies":{"is-network-error":"^1.1.0"},"_hasShrinkwrap":false,"devDependencies":{"xo":"^0.60.0","ava":"^6.3.0","tsd":"^0.32.0","delay":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/p-retry_7.0.0_1755771768473_0.22617152850354372","host":"s3://npm-registry-packages-npm-production"},"readme":"# p-retry\n\n> Retry a promise-returning or async function\n\nIt does exponential backoff and supports custom retry strategies for failed operations.\n\n## Install\n\n```sh\nnpm install p-retry\n```\n\n## Usage\n\n```js\nimport pRetry, {AbortError} from 'p-retry';\n\nconst run = async () => {\n\tconst response = await fetch('https://sindresorhus.com/unicorn');\n\n\t// Abort retrying if the resource doesn't exist\n\tif (response.status === 404) {\n\t\tthrow new AbortError(response.statusText);\n\t}\n\n\treturn response.blob();\n};\n\nconsole.log(await pRetry(run, {retries: 5}));\n```\n\n## API\n\n### pRetry(input, options?)\n\nReturns 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.\n\nDoes not retry on most `TypeErrors`, with the exception of network errors. This is done on a best case basis as different browsers have different [messages](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful) to indicate this. See [whatwg/fetch#526 (comment)](https://github.com/whatwg/fetch/issues/526#issuecomment-554604080)\n\nNon-network `TypeError`s always abort retries, even if `shouldConsumeRetry` or `shouldRetry` would otherwise allow another attempt.\n\n#### input\n\nType: `Function`\n\nReceives the number of attempts as the first argument and is expected to return a `Promise` or any value.\n\n#### options\n\nType: `object`\n\n##### onFailedAttempt(context)\n\nType: `Function`\n\nCallback invoked on each failure. Receives a context object containing the error and retry state information.\n\nThe function is called _after_ `shouldConsumeRetry` and _before_ `shouldRetry`, for all errors _except_ `AbortError`.\n\nIf the function throws, all retries will be aborted and the original promise will reject with the thrown error.\n\n```js\nimport pRetry from 'p-retry';\n\nconst run = async () => {\n\tconst response = await fetch('https://sindresorhus.com/unicorn');\n\n\tif (!response.ok) {\n\t\tthrow new Error(response.statusText);\n\t}\n\n\treturn response.json();\n};\n\nconst result = await pRetry(run, {\n\tonFailedAttempt: ({error, attemptNumber, retriesLeft, retriesConsumed, retryDelay}) => {\n\t\tconsole.log(`Attempt ${attemptNumber} failed. Retrying in ${retryDelay}ms. ${retriesLeft} retries left.`);\n\t\t// 1st request => Attempt 1 failed. Retrying in 1000ms. 5 retries left.\n\t\t// 2nd request => Attempt 2 failed. Retrying in 2000ms. 4 retries left.\n\t\t// …\n\t},\n\tretries: 5\n});\n\nconsole.log(result);\n```\n\nThe `context` object contains:\n- `error` - The error that was thrown\n- `attemptNumber` - The attempt number (starts at 1)\n- `retriesLeft` - Number of retries remaining\n- `retriesConsumed` - Number of retries consumed so far\n- `retryDelay` - The delay in milliseconds before the next retry (based on `minTimeout`, `factor`, `maxTimeout`, and `randomize`). This is `0` when the retry is skipped or when no retry will occur based on the checks completed before the current callback runs.\n\nThe `onFailedAttempt` function can return a promise. For example, to add a [delay](https://github.com/sindresorhus/delay):\n\n```js\nimport pRetry from 'p-retry';\nimport delay from 'delay';\n\nconst run = async () => { … };\n\nconst result = await pRetry(run, {\n\tonFailedAttempt: async () => {\n\t\tconsole.log('Waiting for 1 second before retrying');\n\t\tawait delay(1000);\n\t}\n});\n```\n\n##### shouldRetry(context)\n\nType: `Function`\n\nDecide if a retry should occur based on context. Returning `true` triggers a retry, `false` aborts with the error.\n\nThe function is called _after_ `onFailedAttempt` and `shouldConsumeRetry`.\n\nThe function is _not_ called on `AbortError`, `TypeError` (except network errors), or if `retries` or `maxRetryTime` are exhausted.\n\nIf the function throws, all retries will be aborted and the original promise will reject with the thrown error.\n\n```js\nimport pRetry from 'p-retry';\n\nconst run = async () => { … };\n\nconst result = await pRetry(run, {\n\tshouldRetry: ({error, attemptNumber, retriesLeft}) => !(error instanceof CustomError)\n});\n```\n\nIn the example above, the operation will be retried unless the error is an instance of `CustomError`.\n\n##### shouldConsumeRetry(context)\n\nType: `Function`\n\nDecide if this failure should consume a retry from the `retries` budget.\n\nWhen `false` is returned, the failure will not consume a retry or increment backoff values, but is still subject to `maxRetryTime`.\n\nThe function is called _before_ `onFailedAttempt` and `shouldRetry`.\n\nThe function is _not_ called on `AbortError`.\n\nIf the function throws, all retries will be aborted and the original promise will reject with the thrown error.\n\n```js\nimport pRetry from 'p-retry';\n\nconst run = async () => { … };\n\nconst result = await pRetry(run, {\n\tretries: 2,\n\tshouldConsumeRetry: ({error, retriesLeft}) => !(error instanceof RateLimitError),\n});\n```\n\nIn the example above, `RateLimitError`s will not decrement the available `retries`.\n\n##### retries\n\nType: `number`\\\nDefault: `10`\n\nThe maximum amount of times to retry the operation.\n\n##### factor\n\nType: `number`\\\nDefault: `2`\n\nThe exponential factor to use.\n\n##### minTimeout\n\nType: `number`\\\nDefault: `1000`\n\nThe number of milliseconds before starting the first retry.\n\nSet this to `0` to retry immediately with no delay.\n\n##### maxTimeout\n\nType: `number`\\\nDefault: `Infinity`\n\nThe maximum number of milliseconds between two retries.\n\n##### randomize\n\nType: `boolean`\\\nDefault: `false`\n\nRandomizes the timeouts by multiplying with a factor between 1 and 2.\n\n##### maxRetryTime\n\nType: `number`\\\nDefault: `Infinity`\n\nThe maximum time (in milliseconds) that the retried operation is allowed to run.\n\nMeasured with a monotonic clock (`performance.now()`) so system clock adjustments do not affect the limit.\n\n##### signal\n\nType: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)\n\nYou can abort retrying using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).\n\n```js\nimport pRetry from 'p-retry';\n\nconst run = async () => { … };\nconst controller = new AbortController();\n\ncancelButton.addEventListener('click', () => {\n\tcontroller.abort(new Error('User clicked cancel button'));\n});\n\ntry {\n\tawait pRetry(run, {signal: controller.signal});\n} catch (error) {\n\tconsole.log(error.message);\n\t//=> 'User clicked cancel button'\n}\n```\n\n##### unref\n\nType: `boolean`\\\nDefault: `false`\n\nPrevents retry timeouts from keeping the process alive.\n\nOnly affects platforms with a `.unref()` method on timeouts, such as Node.js.\n\n### makeRetriable(function, options?)\n\nWrap a function so that each call is automatically retried on failure.\n\n```js\nimport {makeRetriable} from 'p-retry';\n\nconst fetchWithRetry = makeRetriable(fetch, {retries: 5});\n\nconst response = await fetchWithRetry('https://sindresorhus.com/unicorn');\n```\n\n### AbortError(message)\n### AbortError(error)\n\nAbort retrying and reject the promise. No callback functions will be called.\n\n### message\n\nType: `string`\n\nAn error message.\n\n### error\n\nType: `Error`\n\nA custom error.\n\n## Tip\n\nYou can pass arguments to the function being retried by wrapping it in an inline arrow function:\n\n```js\nimport pRetry from 'p-retry';\n\nconst run = async emoji => {\n\t// …\n};\n\n// Without arguments\nawait pRetry(run, {retries: 5});\n\n// With arguments\nawait pRetry(() => run('🦄'), {retries: 5});\n```\n\n## FAQ\n\n### How do I mock timers when testing with this package?\n\nThe package uses `setTimeout` and `clearTimeout` from the global scope, so you can use the [Node.js test timer mocking](https://nodejs.org/api/test.html#class-mocktimers) or a package like [`sinon`](https://github.com/sinonjs/sinon).\n\n### How do I stop retries when the process receives SIGINT (Ctrl+C)?\n\nUse an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to signal cancellation on SIGINT, and pass its `signal` to `pRetry`:\n\n```js\nimport pRetry from 'p-retry';\n\nconst controller = new AbortController();\n\nprocess.once('SIGINT', () => {\n\tcontroller.abort(new Error('SIGINT received'));\n});\n\ntry {\n\tawait pRetry(run, {signal: controller.signal});\n} catch (error) {\n\tconsole.log('Retry stopped due to:', error.message);\n}\n```\n\nThe package does not handle process signals itself to avoid global side effects.\n\n## Related\n\n- [p-timeout](https://github.com/sindresorhus/p-timeout) - Timeout a promise after a specified amount of time\n- [More…](https://github.com/sindresorhus/promise-fun)\n","publish_time":1755771768657,"_cnpm_publish_time":1755771768657,"dist-tags":{"latest":"9.0.0","version4":"4.6.2","version7-pre":"7.0.0-0"}}