# async-await-retry

> Simple module to retry a function with async/await syntax !

Latest version **2.1.0** (published 2023-11-21) · MIT license · 0 weekly downloads

## Install

```sh
npm install async-await-retry
pnpm add async-await-retry
yarn add async-await-retry
bun add async-await-retry
```

Provides the command `async-await-retry`.

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.0 |
| Published | 2023-11-21 |
| First published | 2019-01-30 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=7.6.0 |
| Dependencies | 0 |
| Unpacked size | 11.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 25 |
| Author | Vincent Vallet |
| Maintainers | wallet77 |
| Keywords | retry, backoff, repeat, replay, async, await, promises, retries, error |

## Links

- npm: https://www.npmjs.com/package/async-await-retry
- Repository: https://github.com/VoodooTeam/async-await-retry
- Issues: https://github.com/VoodooTeam/async-await-retry/issues
- npm.io page: https://npm.io/package/async-await-retry

## Alternatives

- [@commercetools/sync-actions](https://npm.io/package/@commercetools/sync-actions.md) — 25.1K weekly downloads
- [cwait](https://npm.io/package/cwait.md) — 21.4K weekly downloads
- [@ledgerhq/hw-app-cosmos](https://npm.io/package/@ledgerhq/hw-app-cosmos.md) — 4.2K weekly downloads
- [@financial-times/o-loading](https://npm.io/package/@financial-times/o-loading.md) — 2.8K weekly downloads
- [fa](https://npm.io/package/fa.md) — 185 weekly downloads

## Recent versions

- 2.1.0 (latest) — 2023-11-21
- 2.0.1 — 2022-12-27
- 2.0.0 — 2022-06-30
- 1.2.4 — 2021-11-16
- 1.2.3 — 2021-08-31
- 1.2.2 — 2021-07-20
- 1.2.1 — 2021-03-17
- 1.2.0 — 2020-12-17
- 1.1.2 — 2020-12-09
- 1.1.0 — 2020-07-28
- 1.0.4 — 2019-12-30
- 1.0.3 — 2019-08-30
- 1.0.2 — 2019-07-12
- 1.0.1 — 2019-02-25
- 1.0.0 — 2019-01-30

## README

<div align="center">
<b>Async / Await exponential retry</b><br/>
<br/><br/>
</div>

[![GitHub release](https://img.shields.io/npm/v/async-await-retry.svg)](https://github.com/VoodooTeam/async-await-retry/releases/)
[![GitHub license](https://img.shields.io/github/license/VoodooTeam/async-await-retry.svg)](https://github.com/VoodooTeam/async-await-retry/blob/master/LICENSE)
[![CI pipeline](https://github.com/VoodooTeam/async-await-retry/workflows/Node.js%20CI/badge.svg)](https://github.com/VoodooTeam/async-await-retry/actions?query=workflow%3A%22Node.js+CI%22)
[![Opened issues](https://img.shields.io/github/issues-raw/VoodooTeam/async-await-retry.svg)](https://github.com/VoodooTeam/async-await-retry/issues)
[![Opened PR](https://img.shields.io/github/issues-pr-raw/VoodooTeam/async-await-retry.svg)](https://github.com/VoodooTeam/async-await-retry/pulls)
[![DeepScan grade](https://deepscan.io/api/teams/12068/projects/15025/branches/292974/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=12068&pid=15025&bid=292974)
[![Code coverage](https://codecov.io/gh/VoodooTeam/async-await-retry/branch/master/graph/badge.svg)](https://codecov.io/gh/VoodooTeam/async-await-retry)
[![Node version](https://img.shields.io/node/v-lts/async-await-retry.svg)](https://github.com/VoodooTeam/async-await-retry)


# Purpose

Minimalist, efficient and performance focused retry system.
Basically it helps developer to retry a function with a specific interval, exponential factor etc.

No dependency.

# Compatibility

**/!\ This module use async/await syntax, this is why you must have node 7.6+.**

Supported and tested : >= 7.6

| Version       | Supported     | Tested         |
| ------------- |:-------------:|:--------------:|
| 20.x          | yes           | yes            |
| 18.x          | yes           | yes            |
| 16.x          | yes           | yes            |
| 14.x          | yes           | yes            |
| 12.x          | no            | yes            |
| 10.x          | no            | yes            |
| 9.x           | no            | yes            |
| 8.x           | no            | yes            |
| >= 7.6        | no            | yes            |

# Installation

```console
$ npm install async-await-retry --save
```

# Usage

## Basic usage
```javascript
const retry = require('async-await-retry');

const func = async () => {return new Promise((resolve) => resolve('OK'))};

try {
    const res = await retry(func)
} catch (err) {
    console.log('The function execution failed !')
}
```

## Sync function syntax
```javascript
const retry = require('async-await-retry');

const func = () => {...};

try {
    const res = await retry(func)
    console.log(res) // output : OK
} catch (err) {
    console.log('The function execution failed !')
}
```

## Anonymous function style
```javascript
const retry = require('async-await-retry');

try {
    const res = await retry(async () => {
      return new Promise((resolve) => resolve('OK'))
    })
    
    console.log(res) // output : OK
} catch (err) {
    console.log('The function execution failed !')
}
```

## Callback function style
```javascript
const retry = require('async-await-retry');

try {
    const res = await retry((arg1, cb) => {
        ....
        cb(err, data); // send err as first argument
    }, ["arg1"], {isCb: true});
} catch (err) {
    console.log('The function execution failed !')
}
```

# Options

## retry(function, [args], [config])

* `function` : function to retry in case of error
* `args` : your function's parameters in case you don't use callback style
* `config` : an object containing all retry process options

## options

| Option          | description                                      | Default value    |
| --------------- |:------------------------------------------------:|:----------------:|
| `retriesMax`    | Maximum number of retries                        | 3                |
| `interval`      | Delay in ms between two tentatives               | 0                |
| `exponential`   | Will the interval increase exponentially ?       | true             |
| `maxBackoff`    | Maximum delay before to retry (with exponential) | 30s              |
| `factor`        | The exponential factor to use                    | 2                |
| `jitter`        | Random jitter in ms to add to the interval       | 0                |
| `isCb`          | Old callback function style ?                    | false            |
| `onAttemptFail` | User's callback to manage retry system           | default fallback |


An example of custom options :
```javascript
const retry = require('async-await-retry');

try {
    const res = await retry(async () => {
      return new Promise((resolve) => resolve('OK'))
    }, null, {retriesMax: 4, interval: 100, exponential: true, factor: 3, jitter: 100})
    
    console.log(res) // output : OK
} catch (err) {
    console.log('The function execution failed !')
}
```

## onAttemptFail
This method can be used to manage, by yourself, the retry system.
It's called when an error occurred and before to retry.
This method can have three behaviors:
- you can throw an error
- if it returns truthy value then normal retry system continues
- if it returns falsy value then the retry system stop

```javascript
const retry = require('async-await-retry');

try {
    const res = await retry(MyfuncToRetry, null, {
        onAttemptFail: (data) => {
            // do some stuff here, like logging errors
        }
    });
} catch (err) {
    console.log('The function execution failed !')
}
```

The data argument is an object that can be described like this:

| Property        | description                                |
| --------------- |:------------------------------------------:|
| `error`         | The current error object                   |
| `currentRetry`  | The current retry value                    |
| `retriesMax`    | Maximum number of retries                  |
| `interval`      | Delay in ms between two tentatives         |
| `exponential`   | Will the interval increase exponentially ? |
| `factor`        | The exponential factor to use              |
| `jitter`        | Random jitter in ms to add to the interval |
| `maxBackoff`    | Maximum delay before to retry              |

# Test

```console
$ npm test
```

Coverage report can be found in coverage/.

---
_Source: https://npm.io/package/async-await-retry · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
