@chriscdn/promise-retry
TypeScript icon, indicating that this package has built-in type declarations

2.0.7 • Public • Published

@chriscdn/promise-retry

Retry an asynchronous function until it resolves successfully or exceeds the maximum attempt count.

Installing

Using npm:

npm install @chriscdn/promise-retry

Using yarn:

yarn add @chriscdn/promise-retry

Example 1 - Promises

import promiseRetry from "@chriscdn/promise-retry";

function myFunction(attempt) {
  return new Promise((resolve, reject) => {
    // ... do something

    if (allIsFine) {
      resolve(/* <value> */);
    } else {
      reject(/* <err> */);
    }
  });
}

const options = {
  maxAttempts: 10,
  retryDelay: 0,
  onError: (err, attempt) => {},
};

// Call myFunction until a resolved promise is returned, but not more than 10 times (default is 10)
promiseRetry((attempt) => myFunction(attempt), options)
  .then((value) => {
    // myFunction resolved within 10 attempts
    // value is from the myFunction resolve call
  })
  .catch((err) => {
    // myFunction failed to return a resolved promise within 10 attempts
    // err is the reject value from the last attempt
  });

Example 2 - Async/Await

import promiseRetry from "@chriscdn/promise-retry";

const results = await promiseRetry(
  async (attempt) => {
    // do something async in here
  },
  {
    maxAttempts: 10,
    retryDelay: 0,
    onError: (err, attempt) => {
      // log the error
    },
  }
);

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i @chriscdn/promise-retry

Weekly Downloads

2

Version

2.0.7

License

MIT

Unpacked Size

13.7 kB

Total Files

17

Last publish

Collaborators

  • chriscdn