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

asyncQueue.md

129 lines4.4 KB

1---
2id: asyncQueue
3title: asyncQueue
4---
5​
6```ts
7function asyncQueue<TValue>(fn, initialOptions): (item, position, runOnItemsChange) => boolean;
8```
9​
10Defined in: [async-queuer.ts:982](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-queuer.ts#L982)
11​
12Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.
13The queuer is started automatically and ready to process items.
14​
15Async vs Sync Versions:
16The async version provides advanced features over the sync queue function:
17- Returns promises that can be awaited for task results
18- Built-in retry support via AsyncRetryer integration for each queued task
19- Abort support to cancel in-flight task executions
20- Comprehensive error handling with onError callbacks and throwOnError control
21- Detailed execution tracking (success/error/settle counts)
22- Concurrent execution support (process multiple items simultaneously)
23​
24The sync queue function is lighter weight and simpler when you don't need async features,
25return values, or execution control.
26​
27What is Queuing?
28Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
29Tasks are processed up to the configured concurrency limit. When a task completes,
30the next pending task is processed if the concurrency limit allows.
31​
32Configuration Options:
33- `concurrency`: Maximum number of concurrent tasks (default: 1)
34- `wait`: Time to wait between processing items (default: 0)
35- `maxSize`: Maximum number of items allowed in the queue (default: Infinity)
36- `getPriority`: Function to determine item priority
37- `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')
38- `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')
39- `expirationDuration`: Maximum time items can stay in queue
40- `started`: Whether to start processing immediately (default: true)
41- `asyncRetryerOptions`: Configure retry behavior for task executions
42​
43Error Handling:
44- If an `onError` handler is provided, it will be called with the error and queuer instance
45- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
46- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
47- Both onError and throwOnError can be used together; the handler will be called before any error is thrown
48- The error state can be checked using the underlying AsyncQueuer instance
49​
50State Management:
51- Uses TanStack Store for reactive state management
52- Use `initialState` to provide initial state values when creating the async queuer
53- Use `onSuccess` callback to react to successful task execution and implement custom logic
54- Use `onError` callback to react to task execution errors and implement custom error handling
55- Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
56- Use `onItemsChange` callback to react to items being added or removed from the queue
57- Use `onExpire` callback to react to items expiring and implement custom logic
58- Use `onReject` callback to react to items being rejected when the queue is full
59- The state includes error count, expiration count, rejection count, running status, and success/settle counts
60- State can be accessed via the underlying AsyncQueuer instance's `store.state` property
61- When using framework adapters (React/Solid), state is accessed from the hook's state property
62​
63## Type Parameters
64​
65### TValue
66​
67`TValue`
68​
69## Parameters
70​
71### fn
72​
73(`value`) => `Promise`\<`any`\>
74​
75### initialOptions
76​
77[`AsyncQueuerOptions`](../interfaces/AsyncQueuerOptions.md)\<`TValue`\>
78​
79## Returns
80​
81```ts
83 item,
84 position?,
85 runOnItemsChange?): boolean;
86```
87​
88Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
89Items can be inserted based on priority or at the front/back depending on configuration.
90`undefined` cannot be queued (it is the internal "no item" sentinel) and is always rejected.
91​
92### Parameters
93​
94#### item
95​
96`TValue`
97​
98#### position?
99​
100[`QueuePosition`](../type-aliases/QueuePosition.md) = `...`
101​
102#### runOnItemsChange?
103​
104`boolean` = `true`
105​
106### Returns
107​
108`boolean`
109​
110### Example
111​
112```ts
113queuer.addItem({ value: 'task', priority: 10 });
114queuer.addItem('task2', 'front');
115```
116​
117## Example
118​
119```ts
120const enqueue = asyncQueue<string>(async (item) => {
121 return item.toUpperCase();
122}, {
123 concurrency: 2,
124 wait: 100,
125 onSuccess: (result) => console.log('Processed:', result)
126});
127​
128enqueue('hello');
129```