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

2024-02-05  本文已影响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()
},
}
}

上一篇下一篇

猜你喜欢

热点阅读