@1ib/retry
v1.1.1
Published
A TypeScript utility for retrying sync/async methods that throw errors.
Downloads
12
Readme
retry
A TypeScript utility for retrying sync/async methods that throw errors.
Basic usage:
import { retry } from "@1ib/retry"
class {
// Use the `retry` decorator to retry a method if it throws an error,
// for a maximum of 3 tries.
@retry(3)
foo() {
// This method can return anything or throw an error.
}
}
For async
methods:
class {
// Same as before, but an async function, which means it returns a Promise.
// It also retries up to 3 times if an error is thrown.
@retry(3)
async foo() {
// This method can return anything or throw an error.
}
}
For custom retry logic:
import fs from "fs/promises"
class {
// This method retries up to 3 times if an error is thrown,
// and only if the error is an `ENOENT` or `ENFILE` error.
@retry(async ({ code }: Result | Error, attempts: number) =>
(code === "ENFILE" || code === "EMFILE") && attempts < 3)
async foo(@attempts attemps?: number) {
console.info(`This method has been called ${attempts} times.`)
return fs.readFile("README.md", "utf8")
}
}
Install
Node.js
Install using [npm][npm] or [yarn][yarn]:
npm install @1ib/retry
# or
yarn add @1ib/retry
Import into your Node.js project:
// CommonJS
const { retry } = require("@1ib/retry")
// ESM
import { retry } from "@1ib/retry"
Deno
Install using JSR:
deno add @1ib/retry
#or
jsr add @1ib/retry
Then import into your Deno project:
import { retry } from "@1ib/retry"
Bun
Install using this command:
bun add @1ib/retry
Import into your Bun project:
import { retry } from "@1ib/retry"
License
This project is licensed under the MIT.