$ npm install wing-async-retry
import { runWithLimitedTimes, runWithLimitedTimeout } from 'wing-async-retry';
// Or
<script src='/path/to/wing-async-retry/wing-async-retry.js'></script>;
const { runWithLimitedTimes, runWithLimitedTimeout } = $WingAsyncRetry;
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();
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();
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 } |
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 |