框架
版本
防抖器 API 参考
节流器 API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考

使用异步批处理器

函数: useAsyncBatcher()

ts
function useAsyncBatcher<TValue, TSelected>(
   fn, 
   options, 
selector): ReactAsyncBatcher<TValue, TSelected>
function useAsyncBatcher<TValue, TSelected>(
   fn, 
   options, 
selector): ReactAsyncBatcher<TValue, TSelected>

定义于: react-pacer/src/async-batcher/useAsyncBatcher.ts:167

一个 React hook,用于创建一个 AsyncBatcher 实例来管理异步项目批处理。

这是 useBatcher hook 的异步版本。与同步版本不同,这个异步 batcher

  • 处理 promises 并返回批处理执行的结果
  • 提供可配置错误行为的错误处理
  • 单独跟踪成功、错误和结算计数
  • 具有批处理执行状态的跟踪
  • 返回批处理函数执行的结果

特性

  • 可配置的批处理大小和等待时间
  • 通过 getShouldExecute 进行自定义批处理逻辑
  • 用于监控批处理操作的事件回调
  • 失败批处理操作的错误处理
  • 自动或手动批处理处理

batcher 收集项目,并根据

  • 最大批次大小(每批项目数)
  • 基于时间的批处理(X 毫秒后处理)
  • 通过 getShouldExecute 进行自定义批处理逻辑

错误处理

  • 如果提供了 onError 处理程序,它将使用错误和 batcher 实例进行调用
  • 如果 throwOnError 为 true(当没有提供 onError 处理程序时的默认值),错误将被抛出
  • 如果 throwOnError 为 false(当提供 onError 处理程序时的默认值),错误将被吞没
  • onError 和 throwOnError 可以一起使用 - 在任何错误被抛出之前,处理程序都会被调用
  • 可以使用底层的 AsyncBatcher 实例检查错误状态

状态管理和选择器

该 hook 使用 TanStack Store 进行响应式状态管理。selector 参数允许您指定哪些状态更改将触发重新渲染,通过防止不必要的重新渲染来优化性能。只有当您提供 selector 时,组件才会在选定的状态值发生变化时重新渲染。

默认情况下,不会进行响应式状态订阅,您必须通过提供 selector 函数来选择加入状态跟踪。这可以防止不必要的重新渲染,并让您完全控制组件何时更新。只有当您提供 selector 时,组件才会在选定的状态值发生变化时重新渲染。

可用的状态属性

  • errorCount: 导致错误的批处理执行次数
  • failedItems: 在批处理过程中失败的项目数组
  • isEmpty: batcher 是否没有要处理的项目
  • isExecuting: 当前是否正在异步处理批处理
  • isPending: batcher 是否正在等待超时触发批处理
  • isRunning: batcher 是否处于活动状态并会自动处理项目
  • items: 当前排队等待批量处理的项目数组
  • lastResult: 最近一次批处理执行的结果
  • settleCount: 已完成(成功或错误)的批处理执行次数
  • size: 当前批处理队列中的项目数
  • status: 当前处理状态('idle' | 'pending' | 'executing' | 'populated')
  • successCount: 成功完成的批处理执行次数
  • totalItemsProcessed: 所有批次处理过的项目总数
  • totalItemsFailed: 处理失败的项目总数

类型参数

TValue

TSelected = {}

参数

fn

(items) => Promise<any>

options

AsyncBatcherOptions<TValue> = {}

选择器

(state) => TSelected

Returns (返回)

ReactAsyncBatcher<TValue, TSelected>

示例

tsx
// Basic async batcher for API requests - no reactive state subscriptions
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 }
);

// Opt-in to re-render when execution state changes (optimized for loading indicators)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 },
  (state) => ({
    isExecuting: state.isExecuting,
    isPending: state.isPending,
    status: state.status
  })
);

// Opt-in to re-render when results are available (optimized for data display)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 },
  (state) => ({
    lastResult: state.lastResult,
    successCount: state.successCount,
    totalItemsProcessed: state.totalItemsProcessed
  })
);

// Opt-in to re-render when error state changes (optimized for error handling)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  {
    maxSize: 10,
    wait: 2000,
    onError: (error) => console.error('Batch processing failed:', error)
  },
  (state) => ({
    errorCount: state.errorCount,
    failedItems: state.failedItems,
    totalItemsFailed: state.totalItemsFailed
  })
);

// Complete example with all callbacks
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  {
    maxSize: 10,
    wait: 2000,
    onSuccess: (result) => {
      console.log('Batch processed successfully:', result);
    },
    onError: (error) => {
      console.error('Batch processing failed:', error);
    }
  }
);

// Add items to batch
asyncBatcher.addItem(newItem);

// Manually execute batch
const result = await asyncBatcher.execute();

// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult, size } = asyncBatcher.state;
// Basic async batcher for API requests - no reactive state subscriptions
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 }
);

// Opt-in to re-render when execution state changes (optimized for loading indicators)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 },
  (state) => ({
    isExecuting: state.isExecuting,
    isPending: state.isPending,
    status: state.status
  })
);

// Opt-in to re-render when results are available (optimized for data display)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  { maxSize: 10, wait: 2000 },
  (state) => ({
    lastResult: state.lastResult,
    successCount: state.successCount,
    totalItemsProcessed: state.totalItemsProcessed
  })
);

// Opt-in to re-render when error state changes (optimized for error handling)
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  {
    maxSize: 10,
    wait: 2000,
    onError: (error) => console.error('Batch processing failed:', error)
  },
  (state) => ({
    errorCount: state.errorCount,
    failedItems: state.failedItems,
    totalItemsFailed: state.totalItemsFailed
  })
);

// Complete example with all callbacks
const asyncBatcher = useAsyncBatcher(
  async (items) => {
    const results = await Promise.all(items.map(item => processItem(item)));
    return results;
  },
  {
    maxSize: 10,
    wait: 2000,
    onSuccess: (result) => {
      console.log('Batch processed successfully:', result);
    },
    onError: (error) => {
      console.error('Batch processing failed:', error);
    }
  }
);

// Add items to batch
asyncBatcher.addItem(newItem);

// Manually execute batch
const result = await asyncBatcher.execute();

// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult, size } = asyncBatcher.state;
我们的合作伙伴
Code Rabbit
Unkey
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。