npm.io
1.0.1 • Published 7 years ago

@dyaa/async-retry

Licence
MIT
Version
1.0.1
Deps
0
Size
17 kB
Vulns
0
Weekly
0
DeprecatedThis package is deprecated

@dyaa/async-retry

npm version wercker status contributions welcome Known Vulnerabilities

Problem

We needed a utility that helps us to retry an async function on it's Failure/Rejection and to be able to control the number of retries and the time interval between each retry also to block the retries in case of some logic provided.

Installation
yarn add @dyaa/async-retry

Or if you prefer npm!

npm i @dyaa/async-retry
Usage
import asyncRetry from '@dyaa/async-retry';

asyncRetry expects two parameters

  • The first parameter is a function that returns a Promise.
  • The second parameter is an options object (all of them are optional).
Options Type Optional? Default Description
retries number 5retries number of retries
interval number 5000ms base interval between retries
dontRetry function () => false A function that returns a boolean value. This boolean value is to check if we want the retry to continue or not
onComplete function null A hook function that's called on the completion of the retry also provides (err, count) in params
onFailure function null A hook function that's called on the failure of the retry also provides (err) in params
onRetry function null A hook function that's called on every retry also provides (err, count) in params
Example
import asyncRetry from '@dyaa/async-retry';

const tryFetch = () => fetch('http://www.mocky.io/v2/5c59705d320000f31eba3880')
  .then(res => {
    if (res.status !== 200) {
      return Promise.reject(new Error(`Rejected because of statusCode is ${res.status}`));
    }

    return res.json();
  }).catch(e => Promise.reject(new Error(e)));

asyncRetry(tryFetch, { 
  retries: 3,
  onRetry: (err, count) => console.log(`#### Retry #${count} with ${err}.`),
  onComplete: count => console.log(`#### Completed after ${count} retries.`),
  onFailure: err => console.log(`#### Failed because ${err}.`),
})
  .then(response => {
    console.log({response})
  })
  .catch(console.error);
Inspiration
Thanks
License

MIT License dyaa

Keywords