Batch Calls into One Request
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write createBatcher(batchFn), where batchFn takes an array of keys and returns a promise of an array of results, one for each key, in the same order. Return a function load(key) that returns a promise of the result for that key. Rather than one request per key, collect every load call made in the same synchronous run of code into one call of batchFn, made once that code has finished (in a microtask or a setTimeout of 0, your choice), never during load itself. A key asked for more than once in a batch is sent only once, and every caller for it gets its result. Calls made after a batch has been sent go into a new batch; nothing is cached between batches. If batchFn's promise rejects, every load in that batch rejects with the same reason.
Your code must pass
- Sends calls made together in one batch
- Gives each caller the result for its own key
- Sends a repeated key only once per batch
- Starts a new batch for later calls
- Rejects every caller in a batch when the request fails