Skip to content

Commit

Permalink
feat: docs improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
gperdomor committed Oct 14, 2024
1 parent 7f61be6 commit 5483a64
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
11 changes: 9 additions & 2 deletions src/async/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,24 @@ import { sleep, tryit } from 'radashi'
export type RetryOptions = {
times?: number
delay?: number | null
onRetry?: (err: Error, num: number) => void
onRetry?: (err: Error, attemptNumber: number) => void
backoff?: (count: number) => number
}

/**
* Retries the given function the specified number of times.
*
* @param {Object} options - The employee who is responsible for the project.
* @param {number} [options.times=3] - Number of attempts.
* @param {number} [options.delay] - Specify milliseconds to sleep between attempts.
* @param {Function} [options.onRetry=null] - Is invoked after a new retry is performed. It's passed the Error that triggered it as a parameter and the attempt number.
* @param {Function} [options.backoff=null] - The backoff option is like delay but uses a function to sleep -- makes for easy exponential backoff.
* @param {Function} func - Function to be executed
*
* @see https://radashi.js.org/reference/async/retry
* @example
* ```ts
* const result = await retry({ times: 3, delay: 1000 }, async () => {
* const result = await retry({ times: 3, delay: 1000, onRetry: (err, i) => console.log(`Trying again... Attempt: ${i}`) } }, async () => {
* return await fetch('https://example.com')
* })
* ```
Expand Down
10 changes: 6 additions & 4 deletions tests/async/retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,18 @@ describe('retry', () => {
expect(result).toBe('hello')
})
test('call onRetry function on retries', async () => {
let failedOnce = false
let attempt = 0
const onRetry = vi.fn()
const result = await _.retry({ onRetry }, async _bail => {
if (!failedOnce) {
failedOnce = true
if (attempt < 2) {
attempt++
throw 'Failing for test'
}
return 'hello'
})
expect(onRetry).toBeCalledWith('Failing for test', 1)
expect(onRetry).toBeCalledTimes(2)
expect(onRetry).toHaveBeenNthCalledWith(1, 'Failing for test', 1)
expect(onRetry).toHaveBeenNthCalledWith(2, 'Failing for test', 2)
expect(result).toBe('hello')
})
test('quits on bail', async () => {
Expand Down

0 comments on commit 5483a64

Please sign in to comment.