Query Batching

PromisesPerformanceAsync

Write createBatcher(fetchMany). It returns a function that takes a single id and returns a promise for that id's value.

Every id requested before the next microtask is collected and passed to fetchMany as one array. fetchMany(ids) resolves to an array of values in the same order, and each caller receives only its own.

Examples

Example 1
Input
const load = createBatcher(async (ids) => {
  console.log('one request for', ids);
  return ids.map((id) => 'user-' + id);
});

await Promise.all([load(1), load(2), load(3)]);
Output
one request for [1, 2, 3]
['user-1', 'user-2', 'user-3']
Explanation
Three calls, one request.

Constraints

  • fetchMany resolves to an array the same length as its input

Notes

  • This is what DataLoader does, and how a GraphQL server avoids the N+1 problem.
  • Swap the queue for a fresh array before awaiting, or later calls join a batch that has already gone.

Hints

Read the full write-up for Query Batching
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it