All files / utils loopUntil.ts

100% Statements 13/13
91.67% Branches 11/12
100% Functions 1/1
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                                                                  4x 1x 1x 1x     4x   4x 29x 29x 3x   26x 1x   25x 25x              
import { AsyncOrSync, OneOrMore } from '../types'
import { sample } from 'lodash-uni'
import { wait } from './wait'
 
export interface LoopUntilOptions {
  /**
   * 重试延时,为数组时随机挑选一个。
   */
  retryDelay: OneOrMore<number>
 
  /**
   * 重试限制。
   */
  retryLimit?: number
}
 
export class LoopUntilRetryLimitExceededError extends Error {}
 
export async function loopUntil<T>(
  fn: () => AsyncOrSync<T>,
  condition: (res: T) => AsyncOrSync<boolean>,
  options: LoopUntilOptions,
): Promise<T>
 
export async function loopUntil(
  condition: () => AsyncOrSync<boolean>,
  options: LoopUntilOptions,
): Promise<void>
 
/**
 * 循环调用某个函数直至达到某个条件后返回调用结果。
 *
 * @param fn 要调用的函数
 * @param condition 条件
 * @param options 选项
 */
export async function loopUntil<T>(
  fn: any,
  condition: any,
  options?: any,
): Promise<T> {
  if (options == null) {
    options = condition
    condition = fn
    fn = undefined
  }
 
  let retryCount = 0
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const res = fn ? await fn() : undefined
    if (await condition(res)) {
      return res
    }
    if (options.retryLimit && retryCount >= options.retryLimit) {
      throw new LoopUntilRetryLimitExceededError('已达到最大重试次数')
    }
    retryCount++
    await wait(
      typeof options.retryDelay === 'number'
        ? options.retryDelay
        : sample(options.retryDelay)!,
    )
  }
}