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

Batcher

类:Batcher<TValue>

定义于:batcher.ts:84

一个收集项目并分批处理它们的类。

批处理是一种将多个操作组合在一起作为一个单元进行处理的技术。

Batcher 提供了一种灵活的方式来实现批处理,具有可配置的:

  • 最大批处理大小(每个批处理的项目数)
  • 基于时间的批处理(在 X 毫秒后处理)
  • 通过 getShouldExecute 实现自定义批处理逻辑
  • 用于监控批处理操作的事件回调

示例

ts
const batcher = new Batcher<number>(
  (items) => console.log('正在处理批处理:', items),
  {
    maxSize: 5,
    wait: 2000,
    onExecuteBatch: (items) => console.log('批处理已执行:', items)
  }
);

batcher.addItem(1);
batcher.addItem(2);
// 2 秒后或添加 5 个项目时(以先到者为准),
// 将处理该批处理
// batcher.execute() // 手动触发批处理
const batcher = new Batcher<number>(
  (items) => console.log('正在处理批处理:', items),
  {
    maxSize: 5,
    wait: 2000,
    onExecuteBatch: (items) => console.log('批处理已执行:', items)
  }
);

batcher.addItem(1);
batcher.addItem(2);
// 2 秒后或添加 5 个项目时(以先到者为准),
// 将处理该批处理
// batcher.execute() // 手动触发批处理

类型参数

TValue

构造函数

new Batcher()

ts
new Batcher<TValue>(fn, initialOptions): Batcher<TValue>
new Batcher<TValue>(fn, initialOptions): Batcher<TValue>

定义于:batcher.ts:92

参数

fn

(items) => void

initialOptions

BatcherOptions<TValue>

返回

Batcher<TValue>

方法

addItem()

ts
addItem(item): void
addItem(item): void

定义于:batcher.ts:118

将项目添加到批处理器 如果达到批处理大小、发生超时或 shouldProcess 返回 true,则将处理该批处理

参数

item

TValue

返回

void


execute()

ts
execute(): void
execute(): void

定义于:batcher.ts:146

处理当前批处理的项目。 如果批处理器正在运行并且满足以下任一条件,则此方法将自动触发:

  • 项目数达到 batchSize
  • 等待持续时间已过
  • 添加项目时 getShouldExecute 函数返回 true

您也可以随时手动调用此方法来处理当前批处理。

返回

void


getBatchExecutionCount()

ts
getBatchExecutionCount(): number
getBatchExecutionCount(): number

定义于:batcher.ts:220

返回已处理的批处理次数

返回

number


getIsEmpty()

ts
getIsEmpty(): boolean
getIsEmpty(): boolean

定义于:batcher.ts:199

如果批处理器为空,则返回 true

返回

boolean


getIsRunning()

ts
getIsRunning(): boolean
getIsRunning(): boolean

定义于:batcher.ts:206

如果批处理器正在运行,则返回 true

返回

boolean


getItemExecutionCount()

ts
getItemExecutionCount(): number
getItemExecutionCount(): number

定义于:batcher.ts:227

返回已处理的单个项目总数

返回

number


getOptions()

ts
getOptions(): BatcherOptions<TValue>
getOptions(): BatcherOptions<TValue>

定义于:batcher.ts:110

返回当前批处理器选项

返回

BatcherOptions<TValue>


getSize()

ts
getSize(): number
getSize(): number

定义于:batcher.ts:192

返回批处理器中当前的项目数

返回

number


peekAllItems()

ts
peekAllItems(): TValue[]
peekAllItems(): TValue[]

定义于:batcher.ts:213

返回批处理器中当前所有项目的副本

返回

TValue[]


setOptions()

ts
setOptions(newOptions): void
setOptions(newOptions): void

定义于:batcher.ts:103

更新批处理器选项

参数

newOptions

Partial<BatcherOptions<TValue>>

返回

void


start()

ts
start(): void
start(): void

定义于:batcher.ts:181

启动批处理器并处理任何待处理的项目

返回

void


stop()

ts
stop(): void
stop(): void

定义于:batcher.ts:169

停止批处理器处理批处理

返回

void