npm package: @housinganywhere/async-retry
Description: Async retry with hooks
Author: Dyaa Eldin
Latest version: 1.0.4

### @housinganywhere/async-retry
[![npm version](https://badgen.net/npm/v/@housinganywhere/async-retry)](https://www.npmjs.com/package/@housinganywhere/async-retry)
[![bundle size](https://badgen.net/bundlephobia/minzip/@housinganywhere/async-retry)](https://bundlephobia.com/result?p=@housinganywhere/async-retry)
[![CircleCI](https://circleci.com/gh/housinganywhere/async-retry.svg?style=svg&circle-token=0a935e528125ed305df31bf5c12ef4315f5214a3)](https://circleci.com/gh/housinganywhere/async-retry/tree/master)
[![license](https://badgen.net/npm/license/@housinganywhere/async-retry)](https://github.com/housinganywhere/async-retry/blob/master/LICENSE)


#### 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

```bash
yarn add @housinganywhere/async-retry
```

Or if you prefer npm!

```bash
npm i @housinganywhere/async-retry
```

#### Usage

```ts
import asyncRetry from '@housinganywhere/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   | :heavy_check_mark:  | 5retries    | number of retries                                                                                               |
| interval   | number   | :heavy_check_mark:  | 5000ms      | base interval between retries                                                                                   |
| dontRetry  | function | :heavy_check_mark:  | () => 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 | :heavy_check_mark:  | null        | A hook function that's called on the completion of the retry also provides (err, count) in params                                                                                                              |
| onFailure  | function | :heavy_check_mark:  | null        | A hook function that's called on the failure of the retry also provides (err) in params                                                                                                  |
| onRetry    | function | :heavy_check_mark:  | null        | A hook function that's called on every retry also provides (err, count) in params                                                                                                               |

#### Example

```js
import asyncRetry from '@housinganywhere/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);
```

<!--##### Backoff formula

```ts
/**
 * Backoff formula for more info checkout
 * https://en.wikipedia.org/wiki/Exponential_backoff
 * E -> factor
 * c -> number of trys
 * I -> Interval
 *
 * E(c) = (2^c - 1) / 2
 * E(c) * I
 * @param {number} times - The number of which retry.
 * @param {number} interval - Time interval of last retry in ms.
 * @returns {number} - Number of next retry interval in ms.
 */
```-->

#### Inspiration

- README structure [Kent C. Dodds's Tweet][0]

#### Thanks

- [Christian Gill](https://github.com/gillchristian) for reviewing and providing support.

#### License

[MIT License][1] © [housinganywhere][2]

[0]: https://twitter.com/kentcdodds/status/877189118572191744
[1]: https://github.com/housinganywhere/async-retry/blob/master/LICENSE
[2]: https://housinganywhere.com