防抖节流、并发控制、指数退避重试——我把它收进了一个库 async-concurrency-kit

19 阅读4分钟

前端面试几乎必问手写题:防抖、节流、并发限制、Promise 重试。工作里也天天用:批量上传要控并发、接口抖动要重试、输入框搜索要防抖。

但这些函数散落在各个项目的 utils/ 里,每次新项目都要重抄一遍。我把它们收成一个零依赖 TS 库 async-concurrency-kit,顺便聊聊每道手写题的实现思路。

一、一个库覆盖 6 个高频场景

import { pLimit, pMap, retry, timeout, debounce, throttle } from 'async-concurrency-kit'

// 1. 并发控制:批量上传,同时最多 3 个
const limit = pLimit(3)
await Promise.all(urls.map((url) => limit(() => upload(url))))

// 2. 并发 map:100 条数据,同时最多 5 个,结果顺序不变
const results = await pMap(items, (item) => process(item), 5)

// 3. 指数退避重试:最多 3 次,每次延迟翻倍
const data = await retry(() => fetchData(), { retries: 3, delay: 300, backoff: 2 })

// 4. 超时:3 秒没返回就抛错
const res = await timeout(fetch('/api'), 3000)

// 5. 防抖:停止输入 300ms 后才请求
const onSearch = debounce((kw) => search(kw), 300)

// 6. 节流:滚动每 100ms 最多触发一次
const onScroll = throttle(() => handleScroll(), 100)

二、pLimit:并发控制的经典实现

并发限制的核心是「计数器 + 队列」:超过上限的任务进队列排队,前面有任务完成就放一个出来。

export function pLimit(concurrency: number): LimitFn {
  let active = 0
  const queue: (() => void)[] = []

  const next = () => {
    active--
    queue.shift()?.()
  }

  const run = async <T>(fn: () => Promise<T>): Promise<T> => {
    active++
    try {
      return await fn()
    } finally {
      next()
    }
  }

  return <T>(fn: () => Promise<T>): Promise<T> => {
    if (active < concurrency) {
      return run(fn)
    }
    return new Promise((resolve, reject) => {
      queue.push(() => run(fn).then(resolve, reject))
    })
  }
}

关键点:用 active 计数而不是 Promise.all。任务排队时不能直接调 fn,否则就失去「限流」意义了。任务被 shift 出来才开始真正执行。

pMap 在此基础上保证结果顺序和输入一致——不是谁先完成谁在前,而是按原数组索引放回:

export function pMap<T, R>(items: T[], mapper: (item: T, index: number) => Promise<R>, concurrency: number): Promise<R[]> {
  const limit = pLimit(concurrency)
  return Promise.all(items.map((item, i) => limit(() => mapper(item, i))))
}

Promise.all 本身就保序,所以 pMap 用 Promise.all 包一层 limit 就够了,很干净。

三、retry:指数退避不是「固定间隔」

很多人的重试是「失败后 sleep 固定 1 秒再试」。更好的做法是指数退避:第 1 次等 300ms,第 2 次等 600ms,第 3 次等 1200ms……避免请求风暴,给服务端恢复时间。

export async function retry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
  const { retries = 3, delay = 300, backoff = 2, maxDelay, shouldRetry, onRetry } = options
  let attempt = 0
  let wait = delay

  while (true) {
    try {
      return await fn()
    } catch (err) {
      attempt++
      // 可自定义哪些错误才重试(比如只重试网络错误,不重试业务 4xx)
      if (attempt > retries || (shouldRetry && !shouldRetry(err as Error))) throw err
      onRetry?.(err as Error, attempt)
      await sleep(wait)
      wait = Math.min(wait * backoff, maxDelay ?? Infinity) // 退避封顶,别无限涨
    }
  }
}

两个容易忽略的点:

  1. shouldRetry 回调:不是所有错误都该重试。业务错误(如「余额不足」)重试一百次也没用,只有网络抖动、5xx 才值得重试。把它暴露成可配置,而不是写死。
  2. maxDelay 封顶:指数退避如果不封顶,重试次数多时等待时间会指数爆炸。Math.min(wait * backoff, maxDelay) 兜住。

四、debounce / throttle:绕不开的经典手写题

防抖节流的区别一句话:防抖是「停止触发后延迟执行」,节流是「固定时间间隔内最多执行一次」。

export function debounce<T extends (...args: any[]) => void>(fn: T, wait: number, options: DebounceOptions = {}): DebouncedFunction<T> {
  const { leading = false, trailing = true } = options
  let timer: ReturnType<typeof setTimeout> | null = null
  let lastArgs: Parameters<T> | null = null

  const debounced = function (this: any, ...args: Parameters<T>) {
    lastArgs = args
    if (leading && !timer) fn.apply(this, args)      // 首次立即执行
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      if (trailing && lastArgs) fn.apply(this, lastArgs)
      timer = null
      lastArgs = null
    }, wait)
  }

  debounced.cancel = () => { if (timer) clearTimeout(timer); timer = null }
  debounced.flush = () => { if (timer) { clearTimeout(timer); timer = null; if (lastArgs) fn.apply(undefined, lastArgs) } }

  return debounced
}

这里做了几个「比面试版更完整」的增强:

  1. leading / trailing 选项:leading 控制首次是否立即执行(滚动条一滚就有反馈),trailing 控制停止后是否补一次。
  2. cancel / flush:cancel 取消待执行的任务(比如组件卸载时);flush 立即执行待处理的任务。
  3. 保留 this 和参数:用 function + apply,保证在对象方法上调用不丢 this。

throttle 同理,用时间戳记录上次执行时间,leading 决定第一次是否立即执行:

export function throttle<T extends (...args: any[]) => void>(fn: T, wait: number, options: ThrottleOptions = {}): ThrottledFunction<T> {
  const { leading = true, trailing = true } = options
  let last = 0
  let timer: ReturnType<typeof setTimeout> | null = null

  const throttled = function (this: any, ...args: Parameters<T>) {
    const now = Date.now()
    const remaining = wait - (now - last)
    if (remaining <= 0) {
      if (timer) { clearTimeout(timer); timer = null }
      last = now
      fn.apply(this, args)
    } else if (trailing && !timer) {
      timer = setTimeout(() => { last = Date.now(); timer = null; fn.apply(this, args) }, remaining)
    }
  }
  // ... cancel / flush 略
  return throttled
}

五、timeout:给任意 Promise 加保险

export function timeout<T>(promise: Promise<T>, ms: number, message = 'Timeout'): Promise<T> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error(message)), ms)
    promise.then(
      (v) => { clearTimeout(timer); resolve(v) },
      (e) => { clearTimeout(timer); reject(e) }
    )
  })
}

注意两点:成功/失败都要 clearTimeout(否则定时器挂着不释放);原始 Promise 的 reject 要原样透传,不能吞掉。

写在最后

这些函数每一个单拎出来都不难,难的是把它们做成类型安全、边界处理完善、开箱即用的一个库。面试能讲清楚原理,工作能直接 npm install 用,这两件事这个库都占了。

欢迎 star、提 issue、一起完善。