Async

Async flow control: retry, timeout, polling and sleeping.

retry

Retry a (sync or async) function until it succeeds or retries are exhausted.

import { retry } from '@cc-heart/utils'

const data = await retry(() => fetchData(), {
  retries: 3,          // default: 3
  delay: 1000,         // base delay in ms
  backoff: 'exponential', // 'fixed' | 'linear' | 'exponential'
  jitter: true,
  onRetry: (err, attempt, delay) => console.warn(`attempt ${attempt} failed, next in ${delay}ms`),
})

withTimeout

Race a promise against a time budget. Rejects with TimeoutError when the budget is exceeded (the underlying work is not cancelled — pass an AbortSignal for that).

import { withTimeout, TimeoutError } from '@cc-heart/utils'

try {
  await withTimeout(fetchData(), 3000)
} catch (e) {
  if (e instanceof TimeoutError) console.error('too slow')
}

waitFor

Poll a predicate until it returns a truthy value, or time out.

import { waitFor } from '@cc-heart/utils'

await waitFor(() => document.querySelector('#ready'), { interval: 100, timeout: 5000 })

sleep

Promise-based delay.

import { sleep } from '@cc-heart/utils'

await sleep(1000) // wait 1s

Demo

retry against a flaky function that always fails twice before succeeding:

Loading...

withTimeout racing a slow task against a 1s budget:

Loading...