Skip to main content
Module

x/p_retried/mod.ts>InputOptions

Retry a promise-returning or async function. Abstraction for exponential and custom retry strategies for failed operations
Latest
interface InputOptions
implements [retried.OperationOptions]
import { type InputOptions } from "https://deno.land/x/p_retried@1.0.7/mod.ts";

Properties

optional
onFailedAttempt: (error: RetryError) => void | Promise<void>

Function invoked on each retry. Receives the error thrown by input as the first argument with properties attemptNumber and retriesLeft which indicate the current attempt number and the number of attempts left, respectively.

import pRetried from 'https://deno.land/x/p_retried/mod.ts'

async function run () => {
    const response = await fetch('https://sindresorhus.com/unicorn')
        if (!response.ok) {
            throw new Error(response.statusText)
        }
        return response.json()
    }
}

const result = await pRetried(run, {
   onFailedAttempt: error => {
       console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`); 
       // 1st request => Attempt 1 failed. There are 4 retries left. 
       // 2nd request => Attempt 2 failed. There are 3 retries left. 
       // ...
   },
   retries: 5
})

console.log(result)

The onFailedAttempt function can return a promise. For example, you can do some async logging:

import pRetried from 'https://deno.land/x/p_retried/mod.ts'
import { log } from './async-logger.ts'
const run = async () => { 
    // … 
}

const result = await pRetried(run, {
    onFailedAttempt: async error => {
        await logger.log(error)
    }
})

If the onFailedAttempt function throws, all retries will be aborted and the original promise will reject with the thrown error.

optional
retries: number

Number of tries to retry before rejecting