Skip to content

Jeff-Tian/async-retry.ts

Repository files navigation

async-retry.ts

async await version of co-retry.js, which can be used in both TypeScript and JavaScript.

简体中文

npm download NPM version Build Status Dependencies Status Coverage Status code style: prettier

996.icu LICENSE

[Quality gate](https://sonarcloud.io /dashboard?id=Jeff-Tian_async-retry.ts)

Installation

npm install async-retry.ts --save

# or 

yarn add async-retry.ts

Usage

Simple Usage

TypeScript

for sync
import Action from 'async-retry.ts'

const action = () => {}
const handlers = [
  {
    error: 'error1',
    handler: yourHandler1,
  },
  {
    error: 'error2',
    handler: yourHandler2,
  },
]

Action.retry(action, 3, handlers)
for async
import Action from 'async-retry.ts'

const action = async()=>{}
const handlers = [{
  error: 'error1',
  handler: async yourHandler1()=>{}
}, {
  error: 'error2',
  handler: async yourHandler2()=>{}
}]

await Action.retryAsync(action, 3, handlers)

JavaScript

for sync
const Action = require('async-retry.ts').default

const action = () => {}
const handlers = [
  {
    error: 'error1',
    handler: yourHandler1,
  },
  {
    error: 'error2',
    handler: yourHandler2,
  },
]

Action.retry(action, 3, handlers)
for async
const Action =require('async-retry.ts').default

const action = async()=>{}
const handlers = [{
  error: 'error1',
  handler: async yourHandler1()=>{}
}, {
  error: 'error2',
  handler: async yourHandler2()=>{}
}]

await Action.retryAsync(action, 3, handlers)

An example of retrying with delay

Add delay logic in your error handlers, like so

import Action from 'async-retry.ts'

const action = async()=>{}
const handlers = [{
  error: 'error1',
  handler: async yourHandler1()=>{
    await new Promise(resolve => setTimeout(resolve, 1000))
    // handling
  }
}, {
  error: 'error2',
  handler: async yourHandler2()=>{
    await new Promise(resolve => setTimeout(resolve, 1000))
    // handling...
  }
}]

await Action.retryAsync(action, 3, handlers)

Development

  1. Run after code change

    npm test 
    # or 
    yarn test

    Make sure all tests pass。

  2. git commit

  3. npm version patch/minor/major

  4. npm publish