Framework
Version
Debouncer API Reference
Throttler API Reference
Rate Limiter API Reference
Queue API Reference
Batcher API Reference

AsyncBatcher

Class: AsyncBatcher<TValue>

Defined in: async-batcher.ts:229

A class that collects items and processes them in batches asynchronously.

This is the async version of the Batcher class. Unlike the sync version, this async batcher:

  • Handles promises and returns results from batch executions
  • Provides error handling with configurable error behavior
  • Tracks success, error, and settle counts separately
  • Has state tracking for when batches are executing
  • Returns the result of the batch function execution

Batching is a technique for grouping multiple operations together to be processed as a single unit.

The AsyncBatcher provides a flexible way to implement async batching with configurable:

  • Maximum batch size (number of items per batch)
  • Time-based batching (process after X milliseconds)
  • Custom batch processing logic via getShouldExecute
  • Event callbacks for monitoring batch operations
  • Error handling for failed batch operations

Error Handling:

  • If an onError handler is provided, it will be called with the error and batcher instance
  • If throwOnError is true (default when no onError handler is provided), the error will be thrown
  • If throwOnError is false (default when onError handler is provided), the error will be swallowed
  • Both onError and throwOnError can be used together - the handler will be called before any error is thrown
  • The error state can be checked using the AsyncBatcher instance

State Management:

  • Uses TanStack Store for reactive state management
  • Use initialState to provide initial state values when creating the async batcher
  • Use onSuccess callback to react to successful batch execution and implement custom logic
  • Use onError callback to react to batch execution errors and implement custom error handling
  • Use onSettled callback to react to batch execution completion (success or error) and implement custom logic
  • Use onExecute callback to react to batch execution and implement custom logic
  • Use onItemsChange callback to react to items being added or removed from the batcher
  • The state includes total items processed, success/error counts, and execution status
  • State can be accessed via asyncBatcher.store.state when using the class directly
  • When using framework adapters (React/Solid), state is accessed from asyncBatcher.state

Example

ts
const batcher = new AsyncBatcher<number>(
  async (items) => {
    const result = await processItems(items);
    console.log('Processing batch:', items);
    return result;
  },
  {
    maxSize: 5,
    wait: 2000,
    onSuccess: (result) => console.log('Batch succeeded:', result),
    onError: (error) => console.error('Batch failed:', error)
  }
);

batcher.addItem(1);
batcher.addItem(2);
// After 2 seconds or when 5 items are added, whichever comes first,
// the batch will be processed and the result will be available
// batcher.execute() // manually trigger a batch
const batcher = new AsyncBatcher<number>(
  async (items) => {
    const result = await processItems(items);
    console.log('Processing batch:', items);
    return result;
  },
  {
    maxSize: 5,
    wait: 2000,
    onSuccess: (result) => console.log('Batch succeeded:', result),
    onError: (error) => console.error('Batch failed:', error)
  }
);

batcher.addItem(1);
batcher.addItem(2);
// After 2 seconds or when 5 items are added, whichever comes first,
// the batch will be processed and the result will be available
// batcher.execute() // manually trigger a batch

Type Parameters

TValue

Constructors

new AsyncBatcher()

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

Defined in: async-batcher.ts:236

Parameters

fn

(items) => Promise<any>

initialOptions

AsyncBatcherOptions<TValue>

Returns

AsyncBatcher<TValue>

Properties

options

ts
options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>;
options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>;

Defined in: async-batcher.ts:233


store

ts
readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;

Defined in: async-batcher.ts:230

Methods

addItem()

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

Defined in: async-batcher.ts:287

Adds an item to the async batcher If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed

Parameters

item

TValue

Returns

void


clear()

ts
clear(): void
clear(): void

Defined in: async-batcher.ts:407

Removes all items from the async batcher

Returns

void


flush()

ts
flush(): Promise<any>
flush(): Promise<any>

Defined in: async-batcher.ts:363

Processes the current batch of items immediately

Returns

Promise<any>


peekAllItems()

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

Defined in: async-batcher.ts:389

Returns a copy of all items in the async batcher

Returns

TValue[]


peekFailedItems()

ts
peekFailedItems(): TValue[]
peekFailedItems(): TValue[]

Defined in: async-batcher.ts:393

Returns

TValue[]


reset()

ts
reset(): void
reset(): void

Defined in: async-batcher.ts:414

Resets the async batcher state to its default values

Returns

void


setOptions()

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

Defined in: async-batcher.ts:251

Updates the async batcher options

Parameters

newOptions

Partial<AsyncBatcherOptions<TValue>>

Returns

void


start()

ts
start(): void
start(): void

Defined in: async-batcher.ts:379

Starts the async batcher and processes any pending items

Returns

void


stop()

ts
stop(): void
stop(): void

Defined in: async-batcher.ts:371

Stops the async batcher from processing batches

Returns

void

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.