0.0.2 • Published 11 months ago

wing-async-retry v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

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

PropertyTypeDescriptionRequiredDefault
asyncFnPromiseLikeasynchronous functions. such as promisesYes-
timesNumberThe number of times to retryNo3
timeoutNumberThe timeout that needs to be retried, in msNo5000
delayNumberThe delay of each retry, in msNo500
configConfigFor other configuration items, see ConfigNo{ withCatch: false, debug: false }

Config

PropertyTypeDescriptionRequiredDefault
withCatchBooleanWhether or not to catch an exception or error that ends with a retry via 'try-catch'Nofalse
debugBooleanWhether to enable log outputNofalse
0.0.2

11 months ago

0.0.1

11 months ago