Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

asyncBatch.md

115 lines3.7 KB

1---
2id: asyncBatch
3title: asyncBatch
4---
5​
6```ts
7function asyncBatch<TValue>(fn, options): (item) => Promise<any>;
8```
9​
10Defined in: [async-batcher.ts:588](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-batcher.ts#L588)
11​
12Creates an async batcher that processes items in batches.
13​
14Async vs Sync Versions:
15The async version provides advanced features over the sync batch function:
16- Returns promises that can be awaited for batch results
17- Built-in retry support via AsyncRetryer integration
18- Abort support to cancel in-flight batch executions
19- Cancel support to prevent pending batches from starting
20- Comprehensive error handling with onError callbacks and throwOnError control
21- Detailed execution tracking (success/error/settle counts)
22​
23The sync batch function is lighter weight and simpler when you don't need async features,
24return values, or execution control.
25​
26What is Batching?
27Batching is a technique for grouping multiple operations together to be processed as a single unit.
28​
29Configuration Options:
30- `maxSize`: Maximum number of items per batch (default: Infinity)
31- `wait`: Time to wait before processing batch (default: Infinity)
32- `getShouldExecute`: Custom logic to trigger batch processing
33- `asyncRetryerOptions`: Configure retry behavior for batch executions
34- `started`: Whether to start processing immediately (default: true)
35​
36Error Handling:
37- If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
38- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
39- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
40- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
41- The error state can be checked using the underlying AsyncBatcher instance
42​
43State Management:
44- Uses TanStack Store for reactive state management
45- Use `initialState` to provide initial state values when creating the async batcher
46- Use `onSuccess` callback to react to successful batch execution and implement custom logic
47- Use `onError` callback to react to batch execution errors and implement custom error handling
48- Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
49- Use `onItemsChange` callback to react to items being added or removed from the batcher
50- The state includes total items processed, success/error counts, and execution status
51- State can be accessed via the underlying AsyncBatcher instance's `store.state` property
52- When using framework adapters (React/Solid), state is accessed from the hook's state property
53​
54## Type Parameters
55​
56### TValue
57​
58`TValue`
59​
60## Parameters
61​
62### fn
63​
64(`items`) => `Promise`\<`any`\>
65​
66### options
67​
68[`AsyncBatcherOptions`](../interfaces/AsyncBatcherOptions.md)\<`TValue`\>
69​
70## Returns
71​
72```ts
73(item): Promise<any>;
74```
75​
76Adds an item to the async batcher
77If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
78​
79### Parameters
80​
81#### item
82​
83`TValue`
84​
85### Returns
86​
87`Promise`\<`any`\>
88​
89The result from the batch function, or undefined if an error occurred and was handled by onError
90​
91### Throws
92​
93The error from the batch function if no onError handler is configured or throwOnError is true
94​
95## Example
96​
97```ts
98const batchItems = asyncBatch<number>(
99 async (items) => {
100 const result = await processApiCall(items);
101 console.log('Processing:', items);
102 return result;
103 },
104 {
105 maxSize: 3,
106 wait: 1000,
107 onSuccess: (result) => console.log('Batch succeeded:', result),
108 onError: (error) => console.error('Batch failed:', error)
109 }
110);
111​
112batchItems(1);
113batchItems(2);
114batchItems(3); // Triggers batch processing
115```