框架
版本
Debouncer API 参考
Throttler API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考
批处理器示例

useAsyncThrottler

函数:useAsyncThrottler()

ts
function useAsyncThrottler<TFn>(fn, options): AsyncThrottler<TFn>
function useAsyncThrottler<TFn>(fn, options): AsyncThrottler<TFn>

定义于:react-pacer/src/async-throttler/useAsyncThrottler.ts:55

一个低级别的 React 钩子,用于创建一个 AsyncThrottler 实例,以限制异步函数的执行频率。

此钩子设计灵活且与状态管理无关——它仅返回一个节流器实例,您可以将其与任何状态管理解决方案(useState、Redux、Zustand、Jotai 等)集成。

异步节流确保异步函数在指定的时间窗口内最多执行一次, 无论它被调用多少次。这对于限制昂贵的 API 调用非常有用, 数据库操作或其他异步任务。

与非异步 Throttler 不同,此异步版本支持从节流函数返回值, 使其非常适合 API 调用和其他异步操作,在这些操作中,您希望获得 maybeExecute 调用的结果 而不是在节流函数内部设置状态变量的结果。

错误处理:

  • 如果提供了 onError 处理程序,它将与错误和节流器实例一起被调用
  • 如果 throwOnError 为 true(未提供 onError 处理程序时的默认值),则会抛出错误
  • 如果 throwOnError 为 false(提供 onError 处理程序时的默认值),则会吞没错误
  • onError 和 throwOnError 可以一起使用——处理程序将在抛出任何错误之前被调用
  • 可以使用底层的 AsyncThrottler 实例检查错误状态

类型参数

TFn extends AnyAsyncFunction

参数

fn

TFn

options

AsyncThrottlerOptions<TFn>

返回

AsyncThrottler<TFn>

示例

tsx
// 带返回值的基础 API 调用节流
const { maybeExecute } = useAsyncThrottler(
  async (id: string) => {
    const data = await api.fetchData(id);
    return data; // 返回值被保留
  },
  { wait: 1000 }
);

// 带状态管理和返回值
const [data, setData] = useState(null);
const { maybeExecute } = useAsyncThrottler(
  async (query) => {
    const result = await searchAPI(query);
    setData(result);
    return result; // 返回值可供调用者使用
  },
  {
    wait: 2000,
    leading: true,   // 首次调用立即执行
    trailing: false  // 跳过尾随边缘更新
  }
);
// 带返回值的基础 API 调用节流
const { maybeExecute } = useAsyncThrottler(
  async (id: string) => {
    const data = await api.fetchData(id);
    return data; // 返回值被保留
  },
  { wait: 1000 }
);

// 带状态管理和返回值
const [data, setData] = useState(null);
const { maybeExecute } = useAsyncThrottler(
  async (query) => {
    const result = await searchAPI(query);
    setData(result);
    return result; // 返回值可供调用者使用
  },
  {
    wait: 2000,
    leading: true,   // 首次调用立即执行
    trailing: false  // 跳过尾随边缘更新
  }
);