Provides callback-oriented retry operations with configurable backoff and explicit attempt control.
Downloads / mo 618.4M
Stars 1.3K
Last release 0.13.1
License MIT Strengths Exposes explicit attempt control . Use attempt, retry, and stop to control callback operations. Supports custom delay schedules . Pass an array of timeouts when exponential backoff does not fit. Limitations Callbacks must request another attempt . Call operation.retry(error) to schedule the next attempt. Reports the most frequent error . mainError selects the most frequent message rather than the last failure. $ npm install retry@0.13.1 Copy
import retry from 'retry';
const operation = retry.operation({ retries: 2 });
operation.attempt(attempt => {
const error = attempt < 2 ? new Error('Not ready') : null;
if (operation.retry(error)) return;
console.log(error ?? 'ready');
});
retry examples From open-source projects on GitHub function promiseRetry(fn, options) {
var temp;
var operation;
if (typeof fn === 'object' && typeof options === 'function') {
// Swap options and fn when using alternate signature (options, fn)
temp = options;
options = fn;
fn = temp;
}
operation = retry.operation(options);
return new Promise(function (resolve, reject) {
operation.attempt(function (number) {
Promise.resolve()
.then(function () {
return fn(function (err) {
if (isRetryError(err)) {
err = err.retried;
}
throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
}, number);
})
.then(resolve, function (err) {
if (isRetryError(err)) {
err = err.retried;
if (operation.retry(err || new Error())) {
return;
}
}
reject(err);
});
});
});
}
Show full example Retries selected failures through a shared Retrier queue.
Downloads / mo 607.8M
Last release 0.4.3
License Apache-2.0 $ npm install @humanwhocodes/retry@0.4.3 Copy
import { Retrier } from '@humanwhocodes/retry';
const retrier = new Retrier(error => error.code === 'EMFILE');
const value = await retrier.retry(async () => 'ready');
@humanwhocodes/retry examples From open-source projects on GitHub async write(filePath, contents) {
const value = Buffer.from(contents);
return this.#retrier
.retry(() => this.#fsp.writeFile(filePath, value))
.catch(error => {
// the directory may not exist, so create it
if (error.code === "ENOENT") {
const dirPath = path.dirname(
filePath instanceof URL
? fileURLToPath(filePath)
: filePath,
);
return this.#fsp
.mkdir(dirPath, { recursive: true })
.then(() => this.#fsp.writeFile(filePath, value));
}
throw error;
});
}
Show full example Provides a control-flow toolkit with a built-in retry function.
Downloads / mo 559.9M
Last release 3.2.6
License MIT $ npm install async@3.2.6 Copy
import async from 'async';
const value = await async.retry({ times: 3 }, async () => 'ready');
Async examples From open-source projects on GitHub (results, callback) => {
async.retry(exports.env.options.errors.retry, callback => {
log.debug('Fetching source statistics before starting run');
let source = drivers.get(exports.env.options.drivers.source).driver;
source.getSourceStats(exports.env, (err, sourceStats) => {
exports.env.statistics.source = util._extend(exports.env.statistics.source, sourceStats);
callback(err);
});
}, callback);
}
Show full example Retries promise-returning operations with backoff, retry budgets, and cancellation signals.
Downloads / mo 276.5M
Stars 1.0K
Last release 9.0.0
License MIT Strengths Separates failures from retry budgets . Use shouldConsumeRetry when selected failures should preserve the retry budget. Accepts cancellation signals . Pass an AbortSignal to stop retrying. Limitations Cancellation leaves running attempts active . Pass the signal into the operation to cancel its underlying work. Time limits allow running overruns . Attempts and callbacks can finish after maxRetryTime. $ npm install p-retry@9.0.0 Copy
import pRetry, {AbortError} from 'p-retry';
const run = async () => {
const response = await fetch('https://sindresorhus.com/unicorn');
// Abort retrying if the resource doesn't exist
if (response.status === 404) {
throw new AbortError(response.statusText);
}
return response.blob();
};
console.log(await pRetry(run, {retries: 5}));
p-retry examples From open-source projects on GitHub public async send(message: string | IncomingWebhookSendArguments): Promise<IncomingWebhookResult> {
let payload: IncomingWebhookSendArguments = { ...this.defaults };
if (typeof message === 'string') {
payload.text = message;
} else {
payload = Object.assign(payload, message);
}
// Remove transport options so they don't leak into payloads
const { fetch: _fetch, timeout: _timeout, retryConfig: _retryConfig, ...messagePayload } = payload;
return pRetry(async () => {
const signal = this.timeout > 0 ? AbortSignal.timeout(this.timeout) : undefined;
try {
const response = await this.fetchFn(this.url, {
method: 'POST',
headers: {
...this.headers,
'Content-Type': 'application/json',
},
body: JSON.stringify(messagePayload),
redirect: 'error',
signal,
});
if (!response.ok) {
const body = await response.text();
const httpError = new IncomingWebhookHTTPError(response.status, response.statusText, body);
// Only server errors (5xx) are transient; client errors (4xx), including rate limits (429), fail immediately.
throw response.status >= 500 ? httpError : new AbortError(httpError);
}
return await this.buildResult(response);
} catch (error) {
// Non-retryable signals (AbortError) and already-wrapped errors pass through untouched.
if (error instanceof AbortError || error instanceof SlackWebhookError) {
throw error;
}
// No response received (network/timeout): retryable.
throw new IncomingWebhookRequestError(error instanceof Error ? error : new Error(String(error)));
}
}, this.retryConfig);
}
Show full example Retries promises with an explicit attempt count, exponential delay bounds, and jitter.
Downloads / mo 218.7M
Last release 3.1.3
License Apache-2.0 $ npm install exponential-backoff@3.1.3 Copy
import { backOff } from 'exponential-backoff';
const value = await backOff(async () => 'ready', { numOfAttempts: 3 });
Retries async callbacks with a bail function and node-retry timing options.
Downloads / mo 190.2M
Stars 1.9K
Last release 1.3.3
License MIT Strengths Provides an explicit bailout callback . Call bail for failures that should stop retrying. Supports randomized backoff . Configure exponential delays and randomized timeouts through the retry options. Limitations Bail leaves callback execution active . Return after bail to prevent the callback from continuing. $ npm install async-retry@1.3.3 Copy
import retry from 'async-retry';
const value = await retry(async () => 'ready', { retries: 2 });
async-retry examples From open-source projects on GitHub export async function retry<T>(
fn: asyncRetry.RetryFunction<T>,
retries: number
) {
return await asyncRetry(fn, {
retries,
onRetry(e: unknown, attempt: unknown) {
console.error(
(e as Error).message + `\n\nRetrying ${attempt}/${retries}...`
)
},
minTimeout: 100,
})
}
Show full example Retries promises through an explicit retry callback with the attempt number.
Downloads / mo 136.7M
Last release 2.0.1
License MIT $ npm install promise-retry@2.0.1 Copy
import promiseRetry from 'promise-retry';
const value = await promiseRetry(async () => 'ready', { retries: 2 });
promise-retry examples From open-source projects on GitHub const FetchGet = async (
uri: string,
options: RequestInit,
beforeRetry: PreRetryCallback,
): Promise<Response> =>
await promiseRetry(
(retry, number) =>
fetch(uri, {
...{ method: "GET" },
...CommonOptions,
mode: number <= FetchRetryConfig.retries ? "cors" : "no-cors",
...options,
}).catch((err) => {
beforeRetry && beforeRetry(number);
return retry(err);
}),
FetchRetryConfig,
);
Show full example