@vlsergey/batcher
Small JavaScript module to batch async requests with queue.

Installation
npm i --save @vlsergey/batcher
or
npm i --save-dev @vlsergey/batcher
Usage
const batchFunction = async ( allArgs ) => {
const response = fetch( );
if ( !response.ok ) {
console.error( response );
throw new Error( "Unable to fetch API result: " + response.statusText );
}
return await response.json();
}
const batcher = new Batcher( batchFunction );
const aPromise = batcher.queue( 'Test value' );
aPromise.then( someResultA => { } );
const bPromise = batcher.queue( 'arg0', 'arg1' );
bPromise.then( someResultB => { } );
const allPromises = batcher.queueAll( [ 'arg3' ], [ 'arg3', 'arg4' ] );
allPromises.then( ( values ) => );
const gimmeResultNow = await batcher.queue( someRequest );
API
Constructor
const batcher = new Batcher( batchFunction );
const batcher = new Batcher( batchFunction, options );
Options
delay | 0 | Delay between batch function calls. Ignored if item added to queue. |
flattenArguments | false | If true before call all queued arguments will be flatten to single array (using args.flatMap( a => a ) call). It is useful if Batcher is used for single-key calls. Otherwise it will create problems with multi-argument calls |
maxBatchSize | 50 | max size of batch for single batchFunction call |
maxQueueSize | Number.MAX_SAFE_INTEGER | Max items in queue. Error will be thrown on queue attempt if exceed. |
Methods
queue( arg0, arg1, ... )
-- adds single element to queue. Immediately calls batchFunction
if not in progress.
queueAll( [arg00, arg00], [arg10, arg11], ... )
-- adds multiple elements to queue. Immediately calls batchFunction
if not in progress.