Batch calls made in the same tick
When a list renders, each row may independently request its own data. Batching turns that burst into a single call by collecting every key requested in the current tick and flushing them together once the synchronous code finishes.
Implement createBatcher(handler), returning an object with a load(key) method. load returns a promise. Every key passed to load during the same synchronous run of code joins one batch; the batch is flushed on the microtask queue, so handler is called exactly once with an array of those keys in the order they were requested, duplicates included. handler returns a promise for an array of values in the same order, and each load promise resolves with the value at its own position. A key requested after a flush starts a new batch. If handler rejects, every load promise in that batch rejects with the same reason.
Arguments
handler(keys: Array<any>) => Promise<Array<any>>- Called once per batch with every key requested in that tick. Must resolve with values in the same order as
keys.
Returns
{ load: (key: any) => Promise<any> } — A batcher object whose load returns a promise for the single value at the key's position.
Examples
const batcher = createBatcher(async (ids) => {
// Pretend this is one network call for all ids.
return ids.map((id) => "user:" + id);
});
// Twelve components each ask for one record...
const users = await Promise.all([1, 2, 3].map((id) => batcher.load(id)));
// users === ["user:1", "user:2", "user:3"] — one call collected all three.The DataLoader pattern in a few lines.
What it has to do
- Call
handleronce per batch, with the keys in request order. - Include duplicate keys in the array rather than removing them.
- Resolve each
loadwith the handler value at the matching index. - Flush on the microtask queue, not with
setTimeout. - Reject every
loadin the batch whenhandlerrejects.
Notes
- Flush on the microtask queue (
Promise.resolve().then(flush)) so the batch picks up every key requested during the current synchronous run. - Duplicate keys are kept — removing them changes the handler's output shape and breaks index alignment.
Stuck? The javascript course covers everything this challenge needs.
- 1.collects keys requested in the same tick into one call
- 2.starts a new batch after the previous one flushed
- 3.keeps duplicate keys in the batch
- 4.rejects every load when the handler rejects
- 5.does not call the handler synchronously
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.