A class that allows us to batch function calls that are identical within a
certain time window. This is useful for reducing API calls to external
services, for example.
The Batcher class has an internal cache that stores the results of the
function calls.
The call method takes an array of values as key and an async function fn.
It converts the key to a string and stores it in the cache. If the cache
already has the key, it returns the cached value. Otherwise, it creates a
new promise and sets a timeout for the function call. When the timeout
expires, the function is called and the result is resolved. If an error
occurs, the promise is rejected. Finally, the timeout is removed from the
timeouts property.
A class that allows us to batch function calls that are identical within a certain time window. This is useful for reducing API calls to external services, for example.
The Batcher class has an internal
cache
that stores the results of the function calls.The call method takes an array of values as key and an async function fn. It converts the key to a string and stores it in the cache. If the cache already has the key, it returns the cached value. Otherwise, it creates a new promise and sets a timeout for the function call. When the timeout expires, the function is called and the result is resolved. If an error occurs, the promise is rejected. Finally, the timeout is removed from the timeouts property.
Example