javascript / expert
Snippet
Asynchronous Task Scheduler for React State Updates with Error Recovery
This expert snippet builds a microtask-based asynchronous batching scheduler for React state synchronizations. It collects asynchronous state mutation callbacks and flushes them concurrently inside a microtask queue, wrapping execution in Promise.allSettled and AggregateError for robust error handling.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function createAsyncBatcher(onSync) {let queue = [];let isFlushing = false;return async function schedule(task) {queue.push(task);if (isFlushing) return;isFlushing = true;queueMicrotask(async () => {const batch = queue.splice(0);try {const results = await Promise.allSettled(batch.map(fn => fn()));const errors = results.filter(r => r.status === 'rejected');if (errors.length) throw new AggregateError(errors, 'Batch execution failed');onSync(results.map(r => r.value));} catch (err) {console.error('Batch error:', err);} finally {isFlushing = false;}});};}
react
Breakdown
1
function createAsyncBatcher(onSync) {
Factory function accepting a callback to notify React component state handlers.
2
queueMicrotask(async () => {
Schedules the batch processing execution at the end of the current JavaScript event loop microtask queue.
3
const results = await Promise.allSettled(batch.map(fn => fn()));
Executes queued async operations concurrently while ensuring all promises resolve or reject without early aborting.
4
if (errors.length) throw new AggregateError(errors, 'Batch execution failed');
Aggregates all caught promises rejections into a single handleable exception object.