Convert Figma logo to code with AI

vercel logoasync-retry

Retrying made simple, easy and async

1,920
59
1,920
30

Top Related Projects

Abstraction for exponential and custom retry strategies for failed operations.

Axios plugin that intercepts failed requests and retries them whenever possible

1,009

Retry a promise-returning or async function

Quick Overview

The async-retry library is a utility for retrying asynchronous operations in JavaScript. It provides a simple and flexible way to handle transient errors and network failures by automatically retrying failed operations a specified number of times with configurable backoff strategies.

Pros

  • Flexible Retry Strategies: The library supports various backoff strategies, including exponential, linear, and custom strategies, allowing you to fine-tune the retry behavior to your specific use case.
  • Automatic Retries: The library handles the retry logic for you, so you don't have to write boilerplate code to implement retries manually.
  • Error Handling: The library provides a consistent way to handle errors, including the ability to customize the error handling behavior.
  • Typescript Support: The library is written in TypeScript, providing type safety and better tooling support.

Cons

  • Dependency on Promises: The library is designed to work with asynchronous operations that return Promises, which may not be suitable for all use cases.
  • Limited Concurrency Control: The library does not provide built-in support for controlling the concurrency of retried operations, which may be a concern in some scenarios.
  • Potential Performance Impact: Depending on the number of retries and the backoff strategy, the library may introduce additional latency and performance overhead.
  • Limited Error Reporting: The library's error reporting may not provide detailed information about the root cause of failures, which can make it harder to diagnose and fix issues.

Code Examples

const retry = require('async-retry');

// Retry a function that may fail
const fetchData = async () => {
  return await retry(
    async (bail) => {
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      return await response.json();
    },
    {
      retries: 3,
      factor: 2,
      minTimeout: 1 * 1000,
      maxTimeout: 30 * 1000,
      onRetry: (error, attempt) => {
        console.log(`Retrying (attempt #${attempt}): ${error.message}`);
      },
    }
  );
};

fetchData()
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

This example demonstrates how to use the async-retry library to fetch data from an API, retrying the operation up to 3 times with an exponential backoff strategy.

const retry = require('async-retry');

// Retry a function that may fail with a custom backoff strategy
const fetchData = async () => {
  return await retry(
    async (bail) => {
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      return await response.json();
    },
    {
      retries: 5,
      factor: 1.5,
      minTimeout: 500,
      maxTimeout: 10 * 1000,
      randomize: true,
    }
  );
};

fetchData()
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

This example demonstrates how to use a custom backoff strategy with the async-retry library, where the timeout between retries is randomized within a range.

const retry = require('async-retry');

// Retry a function that may fail with a custom error handler
const fetchData = async () => {
  return await retry(
    async (bail, attempt) => {
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        if (attempt >= 3) {
          bail(new Error(`Maximum retries reached: HTTP error ${response.status}`));
        }
        throw new Error(`HTTP error ${response.status}`);
      }
      return await response.json();
    },
    {
      retries: 5,
      factor: 2,
      minTimeout: 1

Competitor Comparisons

Abstraction for exponential and custom retry strategies for failed operations.

Pros of node-retry

  • More comprehensive retry strategies, including exponential backoff with jitter
  • Supports both callback and promise-based APIs
  • Provides more granular control over retry behavior

Cons of node-retry

  • Larger package size and more dependencies
  • Less focused on async/await syntax
  • Slightly more complex API for basic use cases

Code Comparison

node-retry:

const retry = require('retry');

const operation = retry.operation({
  retries: 3,
  factor: 2,
  minTimeout: 1000,
  maxTimeout: 5000,
  randomize: true
});

operation.attempt(function(currentAttempt) {
  // ... perform operation
});

async-retry:

const retry = require('async-retry');

await retry(async bail => {
  // ... perform operation
}, {
  retries: 3
});

Both libraries provide retry functionality, but node-retry offers more configuration options out of the box. async-retry has a simpler API that integrates well with async/await syntax, making it easier to use in modern JavaScript projects. node-retry's approach allows for more fine-tuned control over retry behavior, while async-retry focuses on simplicity and ease of use with promises.

Axios plugin that intercepts failed requests and retries them whenever possible

Pros of axios-retry

  • Specifically designed for Axios, providing seamless integration with Axios requests
  • Offers more granular control over retry conditions and behaviors
  • Supports custom retry delay algorithms

Cons of axios-retry

  • Limited to Axios library, not as versatile for other HTTP clients or general async operations
  • May have a steeper learning curve due to more configuration options

Code Comparison

axios-retry:

import axios from 'axios';
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });
axios.get('https://example.com/api/data');

async-retry:

import retry from 'async-retry';

await retry(async bail => {
  // Your async operation here
}, { retries: 3 });

Key Differences

  • Scope: axios-retry is specific to Axios, while async-retry is a general-purpose retry utility
  • Configuration: axios-retry offers more Axios-specific options, async-retry is simpler but more flexible
  • Integration: axios-retry integrates directly with Axios instances, async-retry wraps any async function

Use Cases

  • Choose axios-retry for projects heavily reliant on Axios with specific retry requirements
  • Opt for async-retry for general-purpose retry functionality across various async operations

Both libraries serve their purposes well, with axios-retry excelling in Axios-specific scenarios and async-retry offering broader applicability across different types of asynchronous operations.

1,009

Retry a promise-returning or async function

Pros of p-retry

  • More comprehensive error handling with customizable retry strategies
  • Supports both synchronous and asynchronous retry functions
  • Actively maintained with frequent updates and improvements

Cons of p-retry

  • Slightly more complex API, which may be overkill for simple use cases
  • Larger package size due to additional features and dependencies

Code Comparison

p-retry:

import pRetry from 'p-retry';

await pRetry(async () => {
    // Async operation that might fail
}, { retries: 5 });

async-retry:

import retry from 'async-retry';

await retry(async (bail) => {
    // Async operation that might fail
}, { retries: 5 });

Key Differences

  • p-retry uses a more modern Promise-based API, while async-retry uses a callback-style API with a bail function
  • p-retry offers more advanced options for customizing retry behavior, such as exponential backoff and jitter
  • async-retry has a simpler API, making it easier to use for basic retry scenarios
  • p-retry is part of the larger "p" ecosystem of Promise-related utilities by Sindre Sorhus

Use Cases

  • Choose p-retry for complex retry scenarios or when you need fine-grained control over retry behavior
  • Opt for async-retry when simplicity is preferred and basic retry functionality is sufficient

Both libraries are well-maintained and widely used in the Node.js ecosystem, so the choice often comes down to specific project requirements and personal preference.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

async-retry

Retrying made simple, easy, and async.

Usage

// Packages
const retry = require('async-retry');
const fetch = require('node-fetch');

await retry(
  async (bail) => {
    // if anything throws, we retry
    const res = await fetch('https://google.com');

    if (403 === res.status) {
      // don't retry upon 403
      bail(new Error('Unauthorized'));
      return;
    }

    const data = await res.text();
    return data.substr(0, 500);
  },
  {
    retries: 5,
  }
);

API

retry(retrier : Function, opts : Object) => Promise
  • The supplied function can be async or not. In other words, it can be a function that returns a Promise or a value.
  • The supplied function receives two parameters
    1. A Function you can invoke to abort the retrying (bail)
    2. A Number identifying the attempt. The absolute first attempt (before any retries) is 1.
  • The opts are passed to node-retry. Read its docs
    • retries: The maximum amount of times to retry the operation. Default is 10.
    • factor: The exponential factor to use. Default is 2.
    • minTimeout: The number of milliseconds before starting the first retry. Default is 1000.
    • maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity.
    • randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is true.
    • onRetry: an optional Function that is invoked after a new retry is performed. It's passed the Error that triggered it as a parameter.

Authors

NPM DownloadsLast 30 Days