美文网首页
轮询简单封装 - 2024-02-06

轮询简单封装 - 2024-02-06

作者: 勇敢的小拽马 | 来源:发表于2024-02-05 17:16 被阅读0次

    /**

    • 轮询封装
    • @param fn 轮询function
    • @param validate 轮询状态校验规则
    • @param interval 轮询间隔
    • @param retry 网络错误重试次数
    • @returns {poller, stop}
      */
      export function promisePoller(
      fn: (data: { controller?: AbortController }) => Promise<any>,
      validate: (value: any) => boolean,
      interval = 2500,
      retry = 3,
      ): {
      poller: Promise<any>
      stop: (cb?: () => void) => void
      } {
      let timer: any = 0
      // 记录本次请求失败计数
      let failures = 0
      let controller: any
      const clean = () => {
      if (timer) {
      clearTimeout(timer)
      timer = 0
      }
      }

    const resolver = async (resolve: (value: any) => void, reject: (e: any) => void) => {
    try {
    clean()
    // fix: 异步接口请求过程中终止操作失效问题
    if (controller?.signal.aborted) return
    controller = new AbortController()

      const result = await fn({ controller })
      const valid = validate(result)
      // 本次请求成功后, 重置失败计数
      failures = 0
      if (valid === true) {
        clean()
        resolve(result)
      } else if (valid === false) {
        timer = setTimeout(resolver, result.interval || interval, resolve, reject)
      }
    } catch (e) {
      // 网络错误尝试retry
      // TODO 失败类型分类判断
      failures += 1
      if (failures <= retry) {
        timer = setTimeout(resolver, interval, resolve, reject)
        return
      }
      reject(e)
    }
    

    }

    return {
    poller: new Promise(resolver),
    stop: cb => {
    clean()
    controller?.abort()
    if (cb) cb()
    },
    }
    }

    相关文章

      网友评论

          本文标题:轮询简单封装 - 2024-02-06

          本文链接:https://www.haomeiwen.com/subject/fsbqadtx.html