promise-poller vs async-retry vs p-retry vs promise-retry vs retry vs retry-axios
JavaScript Retry Libraries
promise-pollerasync-retryp-retrypromise-retryretryretry-axiosSimilar Packages:

JavaScript Retry Libraries

Retry libraries in JavaScript provide mechanisms to automatically re-attempt failed asynchronous operations, such as network requests or database queries. These libraries help improve the resilience of applications by handling transient errors (temporary issues that may resolve on their own) without requiring manual intervention. They offer configurable options like the number of retries, delay between attempts, and exponential backoff strategies, allowing developers to customize the retry behavior based on their specific use cases. By implementing retries, applications can reduce the impact of temporary failures, enhance user experience, and ensure more reliable data processing.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
promise-poller29,632119-86 years agoMIT
async-retry01,908-305 years agoMIT
p-retry099023.1 kB23 months agoMIT
promise-retry0317-116 years agoMIT
retry01,260-195 years agoMIT
retry-axios050257.8 kB04 months agoApache-2.0

Feature Comparison: promise-poller vs async-retry vs p-retry vs promise-retry vs retry vs retry-axios

Retry Mechanism

  • promise-poller:

    promise-poller is designed for polling a promise-based function until it resolves or reaches a maximum number of attempts. It is useful for scenarios where you need to repeatedly check the status of an operation.

  • async-retry:

    async-retry provides a simple way to retry asynchronous functions with customizable retry logic. It supports exponential backoff and allows you to define when to retry based on the error type.

  • p-retry:

    p-retry focuses on retrying promise-returning functions. It offers a clean API and allows you to specify the number of retries, delay between attempts, and a function to determine if a retry should occur.

  • promise-retry:

    promise-retry allows you to retry a promise-returning function with customizable retry delays. You can specify the number of retries, the delay between attempts, and provide a function to calculate the delay dynamically.

  • retry:

    retry is a versatile library that supports retrying both synchronous and asynchronous functions. It provides extensive configuration options, including customizable retry counts, delay strategies, and error handling.

  • retry-axios:

    retry-axios integrates with Axios to provide automatic retry functionality for HTTP requests. It allows you to configure retry behavior, such as the number of retries and delay between attempts, directly on your Axios instance.

Customization

  • promise-poller:

    promise-poller allows customization of the polling interval, maximum attempts, and the function used to check the promise. You can easily adjust these parameters to fit your use case.

  • async-retry:

    async-retry allows for significant customization, including the ability to define your own retry logic, set maximum retries, and customize the delay between retries. It also supports asynchronous delay functions.

  • p-retry:

    p-retry offers customization for the number of retries, delay between attempts, and the ability to provide a custom retry strategy function. It is designed to be simple and intuitive while allowing for flexibility.

  • promise-retry:

    promise-retry provides customization for the number of retries, delay between retries, and the ability to use a custom delay function. It allows you to define how retries should be handled in a straightforward manner.

  • retry:

    retry offers extensive customization options, including the ability to define your own retry strategy, set maximum retries, and customize delay functions. It is highly configurable and suitable for complex retry scenarios.

  • retry-axios:

    retry-axios allows customization of the retry behavior for Axios requests, including the number of retries, delay between retries, and the ability to specify which HTTP status codes should trigger a retry.

Integration with Promises

  • promise-poller:

    promise-poller integrates well with promise-based functions, allowing you to poll a promise until it resolves. It is particularly useful for scenarios where you need to wait for a promise to complete.

  • async-retry:

    async-retry is designed for asynchronous functions and works seamlessly with promises. It can handle any function that returns a promise, making it versatile for various async operations.

  • p-retry:

    p-retry is built specifically for promise-returning functions, ensuring a smooth integration with asynchronous code. It is lightweight and focuses solely on retrying promises.

  • promise-retry:

    promise-retry is focused on retrying promise-returning functions, making it a great choice for async operations that may fail and need to be retried.

  • retry:

    retry supports both synchronous and asynchronous functions, providing flexibility in how you implement retries. It can handle any function type, including those that return promises.

  • retry-axios:

    retry-axios is specifically designed for Axios, a popular promise-based HTTP client. It adds retry functionality to Axios requests, making it easy to handle failed HTTP calls.

Code Example

  • promise-poller:

    Example of promise-poller

    const promisePoller = require('promise-poller');
    
    async function pollerFunction() {
      // Simulate a polling function
      return new Promise((resolve, reject) => {
        const random = Math.random();
        if (random < 0.8) {
          // 80% chance to fail
          reject(new Error('Not ready'));
        } else {
          // 20% chance to succeed
          resolve('Success!');
        }
      });
    }
    
    async function main() {
      try {
        const result = await promisePoller({
          function: pollerFunction,
          interval: 1000,
          maxAttempts: 10,
        });
        console.log('Polling result:', result);
      } catch (error) {
        console.error('Polling failed:', error);
      }
    }
    
    main();
    
  • async-retry:

    Example of async-retry

    const retry = require('async-retry');
    
    async function fetchData() {
      // Simulate a function that may fail
      throw new Error('Network error');
    }
    
    async function main() {
      try {
        const result = await retry(fetchData, {
          retries: 3,
          factor: 2,
          minTimeout: 1000,
          maxTimeout: 5000,
        });
        console.log('Data:', result);
      } catch (error) {
        console.error('Failed after retries:', error);
      }
    }
    
    main();
    
  • p-retry:

    Example of p-retry

    const { pRetry } = require('p-retry');
    
    async function unreliableFunction() {
      // Simulate a function that fails
      throw new Error('Failed');
    }
    
    async function main() {
      try {
        const result = await pRetry(unreliableFunction, {
          retries: 5,
          onFailedAttempt: (error) => {
            console.log(`Attempt failed: ${error.message}`);
          },
        });
        console.log('Success:', result);
      } catch (error) {
        console.error('All attempts failed:', error);
      }
    }
    
    main();
    
  • promise-retry:

    Example of promise-retry

    const promiseRetry = require('promise-retry');
    
    function unreliableApiCall(retry, attempt) {
      // Simulate an API call that fails
      if (attempt < 3) {
        // Fail the first two attempts
        return retry(new Error('Temporary failure'));
      }
      // Succeed on the third attempt
      return 'Data from API';
    }
    
    promiseRetry((retry) => unreliableApiCall(retry, attempt), {
      retries: 5,
      factor: 2,
      minTimeout: 1000,
      maxTimeout: 4000,
    }).then((result) => {
      console.log('API call succeeded:', result);
    }).catch((error) => {
      console.error('API call failed after retries:', error);
    });
    
  • retry:

    Example of retry

    const retry = require('retry');
    
    function unreliableTask() {
      // Simulate a task that may fail
      return new Promise((resolve, reject) => {
        const random = Math.random();
        if (random < 0.7) {
          // 70% chance of failure
          reject(new Error('Task failed'));
        } else {
          resolve('Task succeeded');
        }
      });
    }
    
    const operation = retry.operation({
      retries: 5,
      factor: 2,
      minTimeout: 1000,
      maxTimeout: 4000,
    });
    
    operation.attempt(async (currentAttempt) => {
      try {
        const result = await unreliableTask();
        console.log(result);
      } catch (error) {
        console.error(`Attempt ${currentAttempt} failed: ${error.message}`);
        if (operation.retry(error)) {
          console.log(`Retrying... (Attempt ${operation.attempts()})`);
        }
      }
    });
    
  • retry-axios:

    Example of retry-axios

    const axios = require('axios');
    const { setup } = require('retry-axios');
    
    const instance = axios.create();
    setup(instance, {
      retries: 3,
      retryDelay: (retryCount) => {
        return retryCount * 1000; // Exponential backoff
      },
    });
    
    async function makeRequest() {
      try {
        const response = await instance.get('https://httpbin.org/status/500');
        console.log('Response:', response.data);
      } catch (error) {
        console.error('Request failed:', error);
      }
    }
    
    makeRequest();
    

How to Choose: promise-poller vs async-retry vs p-retry vs promise-retry vs retry vs retry-axios

  • promise-poller:

    Use promise-poller when you need to poll a promise-based function at regular intervals until it resolves or reaches a maximum number of attempts.

  • async-retry:

    Choose async-retry if you need a simple and flexible solution for retrying asynchronous functions with support for exponential backoff and custom retry logic.

  • p-retry:

    Select p-retry if you want a lightweight library focused on retrying promises with a clean API and built-in support for customizable retry strategies.

  • promise-retry:

    Opt for promise-retry if you require a straightforward way to retry promise-returning functions with support for custom retry delays and error handling.

  • retry:

    Choose retry if you need a versatile library for retrying both synchronous and asynchronous functions, with extensive configuration options for retries, delays, and backoff strategies.

  • retry-axios:

    Select retry-axios if you are working with Axios and want to add automatic retry functionality to your HTTP requests with minimal setup.

README for promise-poller

promise-poller

A basic poller built on top of promises.

Sometimes, you may perform asynchronous operations that may fail. In many of those cases, you want to retry these operations one or more times before giving up. promise-poller handles this elegantly using promises.

Usage

Basic usage

The core of promise-poller is a task function. This is simply a function that starts your asynchronous task and returns a promise. If the task function does not return a promise, it will be wrapped in a promise. To start polling, pass your task function to the promisePoller function:

import promisePoller from 'promise-poller';

function myTask() {
  // do some async stuff that returns a promise
  return promise;
}

var poller = promisePoller({
  taskFn: myTask
});

The promisePoller function will return a "master promise". This promise will be resolved when your task succeeds, or rejected if your task fails and no retries remain.

The master promise will be resolved with the value that your task promise is resolved with. If the poll fails, the master promise will be rejected with an array of all the rejection reasons for each poll attempt.

promise-poller will attempt your task by calling the function and waiting on the returned promise. If the promise is rejected, promise-poller will wait one second and try again. It will attempt to execute your task 3 times before rejecting the master promise.

Use in non-ES2015 environments

promise-poller is written using ES2015 and transpiled with Babel. The main promisePoller function is the default export. If you are using promise-poller in an ES5 environment, you will have to specify the default property when requiring the library in:

var promisePoller = require('promise-poller').default;

Specify polling options

You can specify a different polling interval or number of retries:

var poller = promisePoller({
  taskFn: myTask,
  interval: 500, // milliseconds
  retries: 5
});

Specify timeout

If you want each poll attempt to reject after a certain timeout has passed, use the timeout option:

var poller = promisePoller({
  taskFn: myTask,
  interval: 500,
  timeout: 2000
});

In the above example, the poll is considered failed if it isn't resolved after 2 seconds. If there are retries remaining, it will retry the poll as usual.

Specify "master timeout"

Instead of timing out each poll attempt, you can set a timeout for the entire master polling operation:

var poller = promisePoller({
  taskFn: myTask,
  interval: 500,
  retries: 10,
  masterTimeout: 2000
});

In the above example, the entire poll operation will fail if there is not a successful poll within 2 seconds. This will reject the master promise.

Cancel polling

You may want to cancel the polling early. For example, if the poll fails because of an invalid password, that's not likely to change, so it would be a waste of time to continue to poll. To cancel polling early, return false from the task function instead of a promise.

Alternatively, if your task function involves async work with promises, you can reject the promise with the CANCEL_TOKEN object.

Cancellation example

import promisePoller, { CANCEL_TOKEN } from 'promise-poller';

const taskFn = () => {
  return new Promise((resolve, reject) => {
    doAsyncStuff().then(resolve, error => {
      if (error === 'invalid password') {
        reject(CANCEL_TOKEN); // will cancel polling
      } else {
        reject(error); // will continue polling
      }
    });
  });
}

The shouldContinue function

You can specify an optional shouldContinue function that takes two arguments. The first argument is a rejection reason when a poll fails, and the second argument is the resolved value when a poll succeeds. If the poll attempt failed, and you want to abort further polling, return false from this function. On the other hand, if your poll resolved to a value but you want to keep polling, return true from this function.

Select polling strategy

By default, promise-poller will use a fixed interval between each poll attempt. For example, with an interval option of 500, the poller will poll approximately every 500 milliseconds. This is the fixed-interval strategy. There are two other strategies available that may better suit your use case. To select a polling strategy, specify the strategy option, e.g.:

promisePoller({
  taskFn: myTask,
  strategy: 'linear-backoff'
});

Linear backoff (linear-backoff)

Options:

  • start - The starting value to use for the polling interval (default = 1000)
  • increment - The amount to increase the interval by on each poll attempt.

Linear backoff will increase the interval linearly by some constant amount for each poll attempt. For example, using the default options, the first retry will wait 1000 milliseconds. Each successive retry will wait an additional 1000 milliseconds: 1000, 2000, 3000, 4000, etc.

Exponential backoff with jitter (exponential-backoff)

Options:

  • min - The minimum interval amount to use (default = 1000)
  • max - The maximum interval amount to use (default = 30000)

Exponential backoff increases the poll interval by a power of two for each poll attempt. promise-poller uses exponential backoff with jitter. Jitter takes a random value between min and 2^n on the nth polling interval, not to exceed max.

For more information about exponential backoff with jitter, and its advantages, see https://www.awsarchitectureblog.com/2015/03/backoff.html.

Progress notification

You can also specify a progress callback function. Each time the task fails, the progress callback will be called with the number of retries remaining and the error that occurred (the value that the task promise was rejected with):

function progress(retriesRemaining, error) {
  // log the error?
}

var poller = promisePoller({
  taskFn: myTask,
  interval: 500,
  retries: 5,
  progressCallback: progress
});

Debugging

promise-poller uses the debug library. The debug name is promisePoller. To run your program with debug output for the promise-poller, set the DEBUG environment variable accordingly:

% DEBUG=promisePoller node path/to/app.js

If you have more than one poller active at a time, and you need to differentiate between them in debug output, you can give the promisePoller options a name property:

var poller = promisePoller({
  taskFn: myTask,
  interval: 500,
  retries: 5,
  name: 'App Server Poller'
});

When this poller prints debug messages, the poller name will be included:

promisePoller (App Server Poller) Poll failed. 1 retries remaining. +504ms

Contributors

  • Joe Attardi
  • /u/jcready
  • Jason Stitt
  • Emily Marigold Klassen

License

The MIT License (MIT)

Copyright (c) 2016-2019 Joe Attardi jattardi@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.