Appearance
retryUntil
Repeatedly calls a function until it returns an accepted result.
NOTE
limit guards against looping forever. Once it is reached the most recent result is returned, even though it was never accepted - so check the result if an unaccepted one matters.
Usage
ts
import { random, retryUntil } from 'tsu'
// keep rolling a die until it lands on something other than a 1
retryUntil(
() => random(1, 7),
(roll) => roll !== 1
)
// 2, 3, 4, 5 or 6
retryUntil(
() => random(1, 7),
(roll) => roll === 7,
10
)
// 1, 2, 3, 4, 5 or 6 - no roll is ever accepted, so the 10th roll is returnedType Definitions
ts
/**
* @param fn - The function to call.
* @param accept - The predicate a result must satisfy to be accepted.
* @param limit - The maximum number of attempts.
* @returns The accepted result, or the most recent result if the limit is reached.
*/
function retryUntil<T>(fn: () => T, accept: (result: T) => boolean, limit: number = 1000): T