Async Cargo Adaptive Batch Processing
Buffer a stream of items into adaptive batches with async cargo, flushing on size or timing thresholds so slow items never block the queue.
Code
import cargo from 'async/cargo';
const flush = async (items) => {
console.log('flushing', items.length, 'events');
await new Promise((r) => setTimeout(r, 30));
};
const queue = cargo(flush, 3);
queue.push('event-1');
queue.push('event-2');
queue.push('event-3');
queue.push('event-4');
queue.push(['event-5', 'event-6'], (err) => {
console.log('callback after group drained, err:', err ?? null);
});
const drained = await queue.drain();
console.log('all batches processed:', drained === undefined);
queue.push('event-7');
await queue.idle();How it works
Count the function flush as the entire surface area of Async Cargo Adaptive Batch Processing.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
- Dependency check:
async/cargo— not built-in, must be present in the project.
Using it
Entry signature: const flush = async (items)
Running the file prints labeled results such as flushing, callback after group drained, err:, all batches processed: — each operation’s effect is visible in the output.
Key statements
await new Promise((r) => setTimeout(r, 30));
queue.push(['event-5', 'event-6'], (err) => {
console.log('callback after group drained, err:', err ?? null);
});
const drained = await queue.drain();
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- Yes: `async/cargo` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.