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

fn-retry

v1.0.7

Published

Retry failed function call

Downloads

4

Readme

fn-retry

npm npm GitHub repo GitHub followers Build Status

Installation

npm install fn-retry
yarn add fn-retry

Usage

ES6

import { fnRetry } from 'fn-retry'

// basic example
const fn = () => {
  // function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100, 200, 300],
})
console.log(result)

CommonJS

const { fnRetry } = require('fn-retry')

// basic example
const fn = () => {
  // function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100, 200, 300],
})
console.log(result)

More examples

API

fnRetry

Base strategy with custom delays. Fn will be called at least one time. In case of errors it will wait specified amount of ms (delays array) before the next call.

fnRetry(fn: Function, options: Object) => Promise

fn

Function that should be retried in case of errors

options

| Name | Type | Default | Description | | ------------------ | ----------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | delays | Array | [] | Represents delays (in ms) between failed calls, e.g. [100, 200, 300] - in case of error fn will be called 4 times, with specified delays between calls. | | onCallError | Function | () => null | Called on failed fn call with the object { error: Error, call: number, maxCalls: number } as an argument . It can return optional should-stop-retries value. If returnes true, further retries will be stopped. It can be useful, e.g., in case of auth errors. The default value of the fn can be returned from onMaxCallsExceeded as well. | | onMaxCallsExceeded | Function | () => null | Called when max number of fn calls is exceeded or when retries cancelled by true returned from onCallError. It can return optional default value. | | waiter | Generator | null | If passed, delays option will be ignored. Represents generator of delay values. Can be used for making till-success calls. In this case maxCalls is not passed from onCallError callback. |

Example

// Base example

const fn = () => {
  // some function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetry(fn, {
  delays: [100],
  onCallError: ({ error, call, maxCalls }) =>
    console.log(`Call ${call} of ${maxCalls}: ${error}`),
  onMaxCallsExceeded: () => console.log('max calls exceeded'),
})

// Example with generator, till-success strategy

const fn = () => {
  // ...
}

function* waiter() {
  let waitMs = 100
  while (true) {
    yield waitMs
    waitMs *= 2
  }
}
await fnRetry(fn, {
  waiter,
  onCallError: ({ error, call }) => console.log(`Call ${call}: ${error}`),
})

// Example with generator, custom delays

const fn = () => {
  // ...
}

// it is the same as passing delays: [ 100, 200, 400, 800, 600 ]
function* waiter() {
  let waitMs = 100
  for (let i = 0; i < 5; i++) {
    yield waitMs
    waitMs *= 2
  }
}
await fnRetry(fn, {
  waiter,
  onMaxCallsExceeded: () => ({}),
})

fnRetryWithFibonacci

In case of errors it will wait according to Fibonacci sequence before the next call. Fn will be called at least one time, e.g.:
with calls equal to 5: call failed -> wait 1s -> call failed -> wait 1s -> call failed -> wait 2s -> call failed -> wait 3s -> call failed

fnRetryWithFibonacci(fn: Function, options: Object) => Promise

fn

Function that should be retried in case of errors

options

| Name | Type | Default | Description | | ------------------ | ---------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | calls | number | 1 | Max number of calls, e.g. if calls is equal to 2, then flow will look like: call failed -> wait 1s -> call succeded. | | onCallError | Function | () => null | Called on failed fn call with the object { error: Error, call: number, maxCalls: number } as an argument. It can return optional should-stop-retries value. If returnes true, further retries will be stopped. It can be useful, e.g., in case of auth errors. The default value of the fn can be returned from onMaxCallsExceeded as well. | | onMaxCallsExceeded | Function | () => null | Called when max number of fn calls is exceeded or when retries cancelled by true returned from onCallError. It can return optional default value. |

Example

const fn = () => {
  // some function that should be retried in case of errors
  return 'Hello'
}

const result = await fnRetryWithFibonacci(fn, {
  calls: 2,
  onCallError: ({ error, call, maxCalls }) =>
    console.log(`Call ${call} of ${maxCalls}: ${error}`),
  onMaxCallsExceeded: () => console.log('max calls exceeded'),
})

Higher-order functions: fnRetriable, fnRetriableWithFibonacci

You can use wrapper version of retry functions. They just wrap fn that needs to be retried in case of errors, and return retriable version of the fn. See options in corresponding APIs above. This allows you to use retried version just like you use original fn.

// function that should be retried in case of errors
const getPostById = ({ id }) =>
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`).then(response =>
    response.json()
  )

// wrap getPostById to make it retriable
const getPostByIdWithRetry = fnRetriable(getPostById, {
  delays: [1000],
})
// call retriable version of getPostById
const post = await getPostByIdWithRetry({ id: 1 })
console.log(post)

Testing

Clone the repository and execute:

yarn test
npm test