npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

keep-trying

v2.0.2

Published

A function for creating retryable promises with configurable limit and backoff.

Downloads

7

Readme

keep-trying Build Status

A minimal function to allow retrying promises up to a given limit.

This library was inspired by some callback retry code I used to use, https://github.com/poetic/retryable-promise, and https://github.com/valeriangalliat/promise-retryable.

It is useful when you have some action you need to call that may fail the first time.

The API is intended to be very simple, and leverages the native Promises available in ES2015. May be used with Node 6+, any modern browser, or polyfill that binds to window.Promise.

The keepTrying function returns a promise that will always yield the result of the promise passed to it. If your promise resolves with "Yay!", then keepTrying will resolve that result. The same applies to rejecting.

See the tests directory for extra examples of usage.

Installation

npm install --save keep-trying

Usage

import keepTrying from 'keep-trying';

keepTrying is defined as:

keepTrying = (fn: PromiseFunction<any>, options : Options = {}): Promise<any> => {

interface Options {
  baseTime?: number;
  maxAttempts?: number;
  maxTime?: number;
  backoffStrategy?: BackoffType;
  jitterStrategy?:  JitterType;
  logger?(status: RetryStatus): any;
}

that is,

  • First Argument: A function with no parameters that returns a Promise to be retried on rejection.
  • Second Argument: An Options object that accepts:
    • baseTime: An integer of milliseconds to be used as a base delay time for any strategy. With the exact strategy, the delay between attempts will always be equal to baseTime; linear will be baseTime * attempt, etc.
    • maxAttempts: An integer of how many times to attempt a failed promise. 0 will will cause no retries, 1 will be one retry, etc.
    • maxTime: An integer of milliseconds to act as an upper bound for how long to
    • backoffStrategy: exact, linear, or exponential stategies can be selected, or a custom backoff strategy of type BackoffStrategy may be provided.
    • jitterStrategy: none, full, or equal stategies can be selected, or a custom jitter strategy of type JitterStrategy may be provided.
    • logger: A function that accepts a RetryStatus object as an argument. May be used to log information on failure/try rates or log errors attempts to the console or to a service such as Bugsnag or Sentry.

Examples

import keepTrying from 'keep-trying';
// For Node: const keepTrying = require('keep-trying');

// Create a function that wraps a promise and accepts 0 arguments
const promiseReturningFn = function() {
  return new Promise(function(resolve, reject) {
    const somethingWentWrong = true;
    if (somethingWentWrong) {
      reject(new Error("Something went wrong"));
    } else {
      resolve("Yay!");
    }
  });
};

// Try to resolve the promise from our function up to 3 times
// Uses a backoff of 10ms, multipled by the number of the attempt.
// 150ms is the default, but this example is used in the tests so
// keeping it fast here is good.
keepTrying(promiseReturningFn, { maxAttempts: 3, baseTime: 10 }).then(function(msg) {
  console.log("The promise succeeded!", msg);
}).catch(function(err) {
  console.debug('The promise failed after all 3 attempts :(');
  console.error(err);

  // Rethrow the error if you'd like
  throw err;
});

If you want your attempts logged to console.error or a service such as Bugsnag or Sentry, pass a function that accepts a RetryStatus object as an argument to the options object with the key logger.

keepTrying(promiseReturningFn, {
  maxAttempts: 3,
  baseTime: 500,
  logger(status) { Bugsnag.notifyException(status.error) }
});

// or

keepTrying(promiseReturningFn, {
  maxAttempts: 3,
  baseTime: 500,
  logger(status) {
    // You can make any transformations on the error message here
    // err.message is in the following format:
    // "Failed on attempt 1 of 3: actual_error_message"
    console.debug("promiseReturningFn failed", status.error);
  }
});

Development

  • git clone [email protected]:machuga/keep-trying
  • cd keep-trying
  • npm install
  • npm run build - Generates dist folder
  • npm test - Run mocha test suite

License

MIT