Installations
npm install @n8n/p-retry
Developer
sindresorhus
Developer Guide
Module System
CommonJS
Min. Node Version
>=18.10
Typescript Support
Yes
Node Version
18.18.2
NPM Version
10.5.0
Statistics
799 Stars
64 Commits
66 Forks
7 Watching
2 Branches
21 Contributors
Updated on 26 Nov 2024
Languages
JavaScript (92.42%)
TypeScript (7.58%)
Total Downloads
Cumulative downloads
Total Downloads
533,374
Last day
6.4%
3,188
Compared to previous day
Last week
-1.2%
19,163
Compared to previous week
Last month
2.2%
81,134
Compared to previous month
Last year
0%
533,374
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
p-retry
Retry a promise-returning or async function
It does exponential backoff and supports custom retry strategies for failed operations.
Install
1npm install p-retry
Usage
1import pRetry, {AbortError} from 'p-retry'; 2import fetch from 'node-fetch'; 3 4const run = async () => { 5 const response = await fetch('https://sindresorhus.com/unicorn'); 6 7 // Abort retrying if the resource doesn't exist 8 if (response.status === 404) { 9 throw new AbortError(response.statusText); 10 } 11 12 return response.blob(); 13}; 14 15console.log(await pRetry(run, {retries: 5}));
API
pRetry(input, options?)
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 maximum number of retries is reached. It then rejects with the last rejection reason.
It does not retry on most TypeError
's, with the exception of network errors. This is done on a best case basis as different browsers have different messages to indicate this. See whatwg/fetch#526 (comment)
input
Type: Function
Receives the current attempt number as the first argument and is expected to return a Promise
or any value.
options
Type: object
Options are passed to the retry
module.
onFailedAttempt(error)
Type: Function
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.
1import pRetry from 'p-retry'; 2 3const run = async () => { 4 const response = await fetch('https://sindresorhus.com/unicorn'); 5 6 if (!response.ok) { 7 throw new Error(response.statusText); 8 } 9 10 return response.json(); 11}; 12 13const result = await pRetry(run, { 14 onFailedAttempt: error => { 15 console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`); 16 // 1st request => Attempt 1 failed. There are 4 retries left. 17 // 2nd request => Attempt 2 failed. There are 3 retries left. 18 // … 19 }, 20 retries: 5 21}); 22 23console.log(result);
The onFailedAttempt
function can return a promise. For example, you can do some async logging:
1import pRetry from 'p-retry'; 2import logger from './some-logger'; 3 4const run = async () => { … }; 5 6const result = await pRetry(run, { 7 onFailedAttempt: async error => { 8 await logger.log(error); 9 } 10});
If the onFailedAttempt
function throws, all retries will be aborted and the original promise will reject with the thrown error.
shouldRetry(error)
Type: Function
Decide if a retry should occur based on the error. Returning true triggers a retry, false aborts with the error.
It is not called for TypeError
(except network errors) and AbortError
.
1import pRetry from 'p-retry'; 2 3const run = async () => { … }; 4 5const result = await pRetry(run, { 6 shouldRetry: error => !(error instanceof CustomError); 7});
In the example above, the operation will be retried unless the error is an instance of CustomError
.
signal
Type: AbortSignal
You can abort retrying using AbortController
.
1import pRetry from 'p-retry'; 2 3const run = async () => { … }; 4const controller = new AbortController(); 5 6cancelButton.addEventListener('click', () => { 7 controller.abort(new Error('User clicked cancel button')); 8}); 9 10try { 11 await pRetry(run, {signal: controller.signal}); 12} catch (error) { 13 console.log(error.message); 14 //=> 'User clicked cancel button' 15}
AbortError(message)
AbortError(error)
Abort retrying and reject the promise.
message
Type: string
An error message.
error
Type: Error
A custom error.
Tip
You can pass arguments to the function being retried by wrapping it in an inline arrow function:
1import pRetry from 'p-retry'; 2 3const run = async emoji => { 4 // … 5}; 6 7// Without arguments 8await pRetry(run, {retries: 5}); 9 10// With arguments 11await pRetry(() => run('🦄'), {retries: 5});
Related
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
Found 7/30 approved changesets -- score normalized to 2
Reason
2 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/p-retry/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/p-retry/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:22
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 7 are checked with a SAST tool
Score
4.4
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to @n8n/p-retry
@smithy/middleware-retry
[![NPM version](https://img.shields.io/npm/v/@smithy/middleware-retry/latest.svg)](https://www.npmjs.com/package/@smithy/middleware-retry) [![NPM downloads](https://img.shields.io/npm/dm/@smithy/middleware-retry.svg)](https://www.npmjs.com/package/@smithy
retry
Abstraction for exponential and custom retry strategies for failed operations.
@smithy/util-retry
Shared retry utilities to be used in middleware packages.
promise-retry
Retries a function that returns a promise, leveraging the power of the retry module.