Skip to content

retryUntil

Jason Godesky edited this page Jul 18, 2026 · 1 revision

retryUntil keeps trying its callback function until it returns a value that passes the validator or it has run out of attempts.

Parameters

fn: () => Promise<T>

A method you would like to retry some number of times.

validator: (candidate: T) => boolean

A method that can determine if the value returned from fn is valid or not (returning true means the value is valid and can be returned; returning false means that the value is invalid and we should run fn again).

options: { attempts?: number, fallback: T }

Options for how often to retry fn and what to return if the attempts run out.

options.attempts: number

The number of times retryUntil should run fn before giving up and returning options.fallback.

Default: 10

options.fallback: T

The value that retryUntil should return if it runs out of attempts.

Returns

A valid value produced by fn or options.fallback if it ran out of attempts.

Examples

import { retryUntil } from '@revolutionarygamesco/common'
import randomBetween1And250 from './random250.ts'

/**
 * If randomBetween1And250 returns a number that’s less than 100
 * in its first 10 attempts, randomBetween1And100 will return
 * that. If it doesn’t, then after 10 tries, randomBetween1And100
 * will return 99.
 */

const randomBetween1And100 = async (): number => {
  return await retryUntil(
    randomBetween1And250,
    (candidate: number) => candidate < 100,
    { fallback: 99 }
  )
}

Clone this wiki locally