wing-async-retry
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

wing-async-retry

Install

$ npm install wing-async-retry

Usage

import { runWithLimitedTimes, runWithLimitedTimeout } from 'wing-async-retry';

// Or
<script src='/path/to/wing-async-retry/wing-async-retry.js'></script>;
const { runWithLimitedTimes, runWithLimitedTimeout } = $WingAsyncRetry;

runWithLimitedTimes(asyncFn[, times, delay, config])

Retry a limited number of times

function getData(): Promise<string> {
  return new Promise((resolve, reject) => {
    const random = Math.random();
    setTimeout(() => (random > 0.5 ? resolve('OK') : reject('Error')), random * 1000);
  });
}

async function testLimitedTimes() {
  const [error, data] = await runWithLimitedTimes<string, string>(getData, 2, 300, { debug: true });
  console.log('Result: ', [error, data]);

  // Or
  // withCatch
  try {
    const data = await runWithLimitedTimes<string, string>(getData, 2, 300, { withCatch: true, debug: true });
    console.log('Result-data:', data);
  } catch (error) {
    console.log('Result-error:', error);
  }
}

testLimitedTimes();

runWithLimitedTimeout(asyncFn[, timeout, delay, config])

Retry for a limited time

function getData(): Promise<string> {
  return new Promise((resolve, reject) => {
    const random = Math.random();
    setTimeout(() => (random > 0.5 ? resolve('OK') : reject('Error')), random * 1000);
  });
}

async function testLimitedTimeout() {
  const [error, data] = await runWithLimitedTimeout<string, string>(getData, 6000, 300, { debug: true });
  console.log('Result: ', [error, data]);

  // Or
  // withCatch
  try {
    const data = await runWithLimitedTimeout<string, string>(getData, 6000, 300, { withCatch: true, debug: true });
    console.log('Result-data:', data);
  } catch (error) {
    console.log('Result-error:', error);
  }
}

testLimitedTimeout();

Options

Property Type Description Required Default
asyncFn PromiseLike asynchronous functions. such as promises Yes -
times Number The number of times to retry No 3
timeout Number The timeout that needs to be retried, in ms No 5000
delay Number The delay of each retry, in ms No 500
config Config For other configuration items, see Config No { withCatch: false, debug: false }

Config

Property Type Description Required Default
withCatch Boolean Whether or not to catch an exception or error that ends with a retry via 'try-catch' No false
debug Boolean Whether to enable log output No false

Readme

Keywords

Package Sidebar

Install

npm i wing-async-retry

Weekly Downloads

2

Version

0.0.2

License

MIT

Unpacked Size

25.2 kB

Total Files

9

Last publish

Collaborators

  • wadlay