Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Limit concurrent promises (mapLimit) in JavaScript

111 mapLimit, a ceiling on how much runs at once

hard

Write mapLimit(items, limit, worker): run an async worker over a list with at most limit of them in flight, and return the results in the order of the input. Drive it with an injected clock instead of real timers, and prove the ceiling held, the results kept their order, and the wall time was the ceiling's rather than the sum.

Stuck? Three hints, smallest first
  1. 1. Do not slice the list into batches. A batch waits for its slowest member; a pool of workers pulling from a shared cursor does not.
  2. 2. Start limit loops, each one taking the next index off a shared counter until the list runs out, and Promise.all the loops.
  3. 3. Write into results[i] rather than pushing, and the output order stops depending on which worker finished first.

The answer

/* A clock you drive by hand. advance() drains pending microtasks BEFORE moving the
   time, so work that is about to register its next wait does so against the right now. */
const makeClock = () => {
  let now = 0;
  let seq = 0;
  const timers = [];
  const drainMicrotasks = async () => {
    for (let i = 0; i < 50; i++) await Promise.resolve();
  };
  return {
    now: () => now,
    wait: (ms) => new Promise((resolve) => timers.push({ at: now + ms, seq: seq++, resolve })),
    async runAll() {
      await drainMicrotasks();
      while (timers.length) {
        timers.sort((a, b) => a.at - b.at || a.seq - b.seq);
        const next = timers.shift();
        now = next.at;
        next.resolve();
        await drainMicrotasks();
      }
      return now;
    },
  };
};

const mapLimit = async (items, limit, worker) => {
  const results = new Array(items.length);
  let cursor = 0;
  const runner = async () => {
    while (cursor < items.length) {
      const i = cursor++;                       // claim an index, then await
      results[i] = await worker(items[i], i);
    }
  };
  const pool = Array.from({ length: Math.min(limit, items.length) }, runner);
  await Promise.all(pool);
  return results;
};

const routes = [
  { name: 'yaba', ms: 30 },
  { name: 'ikeja', ms: 10 },
  { name: 'lekki', ms: 20 },
  { name: 'ojota', ms: 5 },
  { name: 'apapa', ms: 15 },
];

const quoteAll = async (limit) => {
  const clock = makeClock();
  const finished = [];
  let inFlight = 0;
  let peak = 0;
  const quote = async (route) => {
    inFlight++;
    peak = Math.max(peak, inFlight);
    await clock.wait(route.ms);
    inFlight--;
    finished.push(route.name);
    return `${route.name}:${route.ms}`;
  };
  const pending = mapLimit(routes, limit, quote);
  const finishedAt = await clock.runAll();
  const results = await pending;
  return { results, finished, peak, finishedAt };
};

const two = await quoteAll(2);
const serial = await quoteAll(1);
const wideOpen = await quoteAll(5);
const overshoot = await quoteAll(50);
const orderIsStable = same(two.results, serial.results) && same(two.results, wideOpen.results);

console.log('limit 2 :', two.finished, '| peak:', two.peak, '| clock:', two.finishedAt);
console.log('limit 1 :', serial.finished, '| clock:', serial.finishedAt);
console.log('limit 5 :', wideOpen.finished, '| clock:', wideOpen.finishedAt);
console.log('results :', two.results);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('results come back in the order of the input, whatever the finishing order', two.results, ['yaba:30', 'ikeja:10', 'lekki:20', 'ojota:5', 'apapa:15']);
test('never more than two in flight, even though five were queued', two.peak, 2);
test('they finished in duration order, not input order', two.finished, ['ikeja', 'yaba', 'lekki', 'ojota', 'apapa']);
test('and the batch took 45 on the injected clock, not the 80 a serial run would cost', two.finishedAt, 45);
test('a limit of one is exactly serial: input order, and the sum of the durations', [serial.peak, serial.finished, serial.finishedAt], [1, ['yaba', 'ikeja', 'lekki', 'ojota', 'apapa'], 80]);
test('a limit as wide as the list starts everything, so the total is the longest job', [wideOpen.peak, wideOpen.finishedAt], [5, 30]);
test('a limit larger than the list starts one worker per item and no more', [overshoot.peak, overshoot.finishedAt], [5, 30]);
test('only the timing changed: every limit produced the same answers', orderIsStable, true);

The pool is the idea. Chunking the list into groups of limit and awaiting each group is the obvious approach and it is measurably worse: every chunk waits for its slowest member before the next one starts, so one slow item stalls a whole group. Workers pulling from a shared cursor keep the pipe full — the moment ikeja finishes at 10, that worker takes lekki, without waiting for yaba.

cursor++ claims an index synchronously, before any await, which is what makes the shared counter safe. There are no threads here: between the read and the increment nothing else can run, because nothing else runs until this function reaches an await. Move the increment after the await and two workers happily take the same item.

Writing to results[i] rather than pushing is what separates completion order from result order, and the assertions keep the two apart on purpose: the finishing order is by duration, the result order is by input, and the answers are identical for every limit. The limit only buys you time — and protection, since the reason to cap concurrency is usually a server that will rate-limit you or a phone that will run out of sockets. Note also that Promise.all over the pool means one rejection abandons the batch with results half-filled; wrap the worker in a try/catch and record failures if you want the rest to continue.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.