AniUI Academy

Batch calls made in the same tick

mediumAsync & Promises+250 XPPractice

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 handler once per batch, with the keys in request order.
  • Include duplicate keys in the array rather than removing them.
  • Resolve each load with the handler value at the matching index.
  • Flush on the microtask queue, not with setTimeout.
  • Reject every load in the batch when handler rejects.

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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.