Skip to content
Onsite

Batch Async Calls

HardP3Coding

Implement createBatcher(batchFn), a DataLoader-style helper that turns many single lookups into one batched call.

batchFn(keys) is an async function that takes an array of keys and returns a promise of an array of results in the same order and with the same length. createBatcher returns a function load(key) that returns a promise for that key's result.

  • All load calls made in the same synchronous run (before the current call stack unwinds and microtasks run) are collected and answered by one call to batchFn.
  • The same key requested several times in one batch is sent once; every caller gets the same result.
  • Calls made after that batch was dispatched start a new batch.
  • If batchFn rejects, every promise of that batch rejects with the same error. If it returns something that is not an array of the same length as the keys, every promise of that batch rejects with an Error whose message contains "same length".

Example 1

Input
const load = createBatcher(async (ids) => ids.map(id => id * 10)); const [a, b] = await Promise.all([load(1), load(2)]);
Output
a = 10, b = 20, and batchFn ran once with [1, 2]

Constraints

  • Keys are primitives (compared like Map keys).
  • At most 10^4 calls per batch.

Hints

Run checks the 3 visible tests, Submit all 10.