All files / utils wait.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 6/6
100% Lines 10/10

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                                                  83x 83x   83x 83x                               34x       3x 3x 2x   3x 3x    
/**
 * @public
 */
export interface WaitResult<T> extends Promise<T> {
  /**
   * 取消等待,不执行后续逻辑。
   */
  cancel: () => void
}
 
/**
 * 等待一段时间 resolve。
 *
 * @public
 * @param milliseconds 等待时间(毫秒)
 * @param value resolve 值
 * @example
 * ```typescript
 * wait(1000).then(() => {
 *   console.log('ok')
 * }) // => 1秒后在控制台打印字符串: ok
 * ```
 */
export function wait<T>(milliseconds: number, value?: T): WaitResult<T> {
  let timer: any
  const result = new Promise<T | undefined>(resolve => {
    timer = setTimeout(() => resolve(value), milliseconds)
  }) as WaitResult<T>
  result.cancel = () => clearTimeout(timer)
  return result
}
 
/**
 * 等待一段时间后 reject。
 *
 * @public
 * @param milliseconds 等待时间(毫秒)
 * @param value reject 值
 * @example
 * ```typescript
 * wait.reject(1000).catch(() => {
 *   console.log('ok')
 * }) // => 1秒后在控制台打印字符串: ok
 * ```
 */
wait.reject = function reject(
  milliseconds: number,
  value?: any,
): WaitResult<never> {
  const waitRes = wait(milliseconds)
  const res: WaitResult<never> = waitRes.then(() =>
    Promise.reject(value),
  ) as any
  res.cancel = waitRes.cancel
  return res
}