Function: asyncBatch()
function asyncBatch<TValue>(fn, options): (item) => void
function asyncBatch<TValue>(fn, options): (item) => void
Defined in: async-batcher.ts:440
Creates an async batcher that processes items in batches
Unlike the sync batcher, this async version:
- 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
Error Handling:
- If an onError handler is provided, it will be called with the error, the batch of items that failed, 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 underlying 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 the underlying AsyncBatcher instance's store.state property
- When using framework adapters (React/Solid), state is accessed from the hook's state property
Type Parameters
• TValue
Parameters
fn
(items) => Promise<any>
options
AsyncBatcherOptions<TValue>
Returns
Function
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
Example
const batchItems = asyncBatch<number>(
async (items) => {
const result = await processApiCall(items);
console.log('Processing:', items);
return result;
},
{
maxSize: 3,
wait: 1000,
onSuccess: (result) => console.log('Batch succeeded:', result),
onError: (error) => console.error('Batch failed:', error)
}
);
batchItems(1);
batchItems(2);
batchItems(3); // Triggers batch processing
const batchItems = asyncBatch<number>(
async (items) => {
const result = await processApiCall(items);
console.log('Processing:', items);
return result;
},
{
maxSize: 3,
wait: 1000,
onSuccess: (result) => console.log('Batch succeeded:', result),
onError: (error) => console.error('Batch failed:', error)
}
);
batchItems(1);
batchItems(2);
batchItems(3); // Triggers batch processing