about summary refs log tree commit diff
path: root/src/lib/async/retry.ts
blob: 8a1729091dbf7e50491140193f81a70c93848000 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import {timeout} from '#/lib/async/timeout'
import {isNetworkError} from '#/lib/strings/errors'

export async function retry<P>(
  retries: number,
  shouldRetry: (err: any) => boolean,
  action: () => Promise<P>,
  delay?: number,
): Promise<P> {
  let lastErr
  while (retries > 0) {
    try {
      return await action()
    } catch (e: any) {
      lastErr = e
      if (shouldRetry(e)) {
        if (delay) {
          await timeout(delay)
        }
        retries--
        continue
      }
      throw e
    }
  }
  throw lastErr
}

export async function networkRetry<P>(
  retries: number,
  fn: () => Promise<P>,
): Promise<P> {
  return retry(retries, isNetworkError, fn)
}