An async event wrapper that allows multiple calls in an interval
to be batched together, and only call the underlying function once.
Optionally, the output can be unbatched to match the inputs.
Example
The API is a lot like debounce, but with an additional batch function
and an optional unbatch function.
import { batch } from"@pistonite/pure/sync";
constexecute = batch({ fn: (n: number) => { console.log(n); }, interval:100, // batch receives all the inputs and returns a single input // here we just sums the inputs batch: (args: [number][]): [number] => [args.reduce((acc, [n]) =>acc + n, 0)], });
awaitexecute(1); // logs 1 immediately constp1 = execute(2); // will be resolved at 100ms constp2 = execute(3); // will be resolved at 100ms awaitPromise.all([p1, p2]); // logs 5 after 100ms
Unbatching
The optional unbatch function allows the output to be unbatched,
so the promises are resolved as if the underlying function is called
directly.
Note that unbatching is usually slow and not required.
An async event wrapper that allows multiple calls in an interval to be batched together, and only call the underlying function once.
Optionally, the output can be unbatched to match the inputs.
Example
The API is a lot like
debounce
, but with an additionalbatch
function and an optionalunbatch
function.Unbatching
The optional
unbatch
function allows the output to be unbatched, so the promises are resolved as if the underlying function is called directly.Note that unbatching is usually slow and not required.