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

createBatcher

函数:createBatcher()

ts
function createBatcher<TValue>(fn, initialOptions): SolidBatcher<TValue>
function createBatcher<TValue>(fn, initialOptions): SolidBatcher<TValue>

定义于:batcher/createBatcher.ts:90

创建一个与 Solid 兼容的 Batcher 实例,用于管理项目批处理,并为所有有状态属性公开 Solid 信号。

特性:

  • 使用提供的 fn 函数对项目进行批处理
  • 可配置的批处理大小和等待时间
  • 通过 getShouldExecute 实现自定义批处理逻辑
  • 用于监控批处理操作的事件回调
  • 所有有状态属性(项目、计数等)都作为 Solid 信号公开以实现响应性

批处理器根据以下条件收集项目并进行批处理:

  • 最大批处理大小
  • 基于时间的批处理(在 X 毫秒后处理)
  • 通过 getShouldExecute 实现自定义批处理逻辑

示例用法:

tsx
const batcher = createBatcher(
  (items) => {
    // 处理项目批处理
    console.log('正在处理批处理:', items);
  },
  {
    maxSize: 5,
    wait: 2000,
    onExecute: (batcher) => console.log('批处理已执行'),
    getShouldExecute: (items) => items.length >= 3
  }
);

// 将项目添加到批处理
batcher.addItem('task1');
batcher.addItem('task2');

// 控制批处理器
batcher.stop();  // 暂停处理
batcher.start(); // 恢复处理

// 通过信号访问批处理器状态
console.log('项目:', batcher.allItems());
console.log('大小:', batcher.size());
console.log('是否为空:', batcher.isEmpty());
console.log('是否正在运行:', batcher.isRunning());
console.log('批处理计数:', batcher.batchExecutionCount());
console.log('项目计数:', batcher.itemExecutionCount());
const batcher = createBatcher(
  (items) => {
    // 处理项目批处理
    console.log('正在处理批处理:', items);
  },
  {
    maxSize: 5,
    wait: 2000,
    onExecute: (batcher) => console.log('批处理已执行'),
    getShouldExecute: (items) => items.length >= 3
  }
);

// 将项目添加到批处理
batcher.addItem('task1');
batcher.addItem('task2');

// 控制批处理器
batcher.stop();  // 暂停处理
batcher.start(); // 恢复处理

// 通过信号访问批处理器状态
console.log('项目:', batcher.allItems());
console.log('大小:', batcher.size());
console.log('是否为空:', batcher.isEmpty());
console.log('是否正在运行:', batcher.isRunning());
console.log('批处理计数:', batcher.batchExecutionCount());
console.log('项目计数:', batcher.itemExecutionCount());

类型参数

TValue

参数

fn

(items) => void

initialOptions

BatcherOptions<TValue> = {}

返回

SolidBatcher<TValue>