Skip to content

Checkpoint: Ordered Work

The Course
•
25 min study

Today's lessons gave you three separate rules: keep results in input order, never have more than limit jobs running, and refill a free slot as soon as one finishes rather than waiting for a whole batch. Cancellation added a fourth: a signal that is already aborted must stop work before any of it starts. This checkpoint asks for all four in one small function, limitedMap(values, mapper, limit, signal).

It is the worker loop from the concurrency lesson, with validation and a pre-abort check. It does not yet handle a failing mapper or an abort that arrives mid-run; Day 7's pool adds those. What is new is the evidence. The test records which calls have started and the peak number active at once, and it releases calls out of order with deferred promises, so "a slot was refilled" is something you can see in the output rather than infer from timing.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
async function main() {
  let resolveFirst;
  const first = new Promise(resolve => {
    resolveFirst = resolve;
  });
  const second = Promise.resolve("B");
  const work = Promise.all([first, second]);

  resolveFirst("A");
  console.log((await work).join(","));
}

main();
Check your prediction
Text
A,B

Acceptance cases before you code

Write a small test plan before implementing controlled output ordering. These cases extend the brief; they are not a second worked solution. Predict the expected behavior independently, then test through the public function. A good ordinary example and a good boundary example should catch different possible mistakes.

Case to tryWhat your result should demonstrate
Four values, limit 2, nothing released yetExactly calls 0 and 1 have started
Release call 1 before call 0Call 2 starts without waiting for call 0 (a refill, not a batch)
Release the rest in any orderResults are in input order and the peak active count is 2
Signal already abortedRejects with the signal's reason; the mapper is never called
Limit 0RangeError, before any call starts

After the core task passes, deliberately break one rule and identify the case that notices it. Restore the implementation and explain the failure in terms of the contract, not the number of assertions. If a case requires a concept you have not recalled, revisit the relevant lesson before opening the solution.

Your turn

Exercise

Checkpoint: a two-slot runner

Write limitedMap(values, mapper, limit, signal) so that every acceptance case passes. The mapper is called as mapper(value, index). The test harness below it is complete: it holds each call on a deferred promise and releases them in the order shown. Print:

Text
started: 0,1
after releasing 1: 0,1,2
results: A,B,C,D | peak: 2
pre-aborted: not needed | calls: 0
RangeError: limit must be a positive integer
Your workspace JavaScript
async function main() {
  async function limitedMap(values, mapper, limit, signal) {
    // First version: starts every call at once. Add the limit check,
    // the pre-abort check and worker slots.
    return Promise.all(values.map((value, index) => mapper(value, index)));
  }

  // ---- test harness: each call waits until the test releases it ----
  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }
  const tick = () => new Promise(resolve => setTimeout(resolve, 0));

  const gates = [];
  const started = [];
  let active = 0;
  let peak = 0;

  async function mapper(value, index) {
    started.push(index);
    active += 1;
    peak = Math.max(peak, active);
    gates[index] = deferred();
    await gates[index].promise;
    active -= 1;
    return value.toUpperCase();
  }

  const run = limitedMap(["a", "b", "c", "d"], mapper, 2, new AbortController().signal);
  await tick();
  console.log(`started: ${started.join(",")}`);

  gates[1].resolve();
  await tick();
  console.log(`after releasing 1: ${started.join(",")}`);

  gates[0].resolve();
  await tick();
  gates[2].resolve();
  gates[3].resolve();
  console.log(`results: ${(await run).join(",")} | peak: ${peak}`);

  const stopped = new AbortController();
  stopped.abort("not needed");
  let calls = 0;
  try {
    await limitedMap(["x"], async () => calls++, 2, stopped.signal);
  } catch (reason) {
    console.log(`pre-aborted: ${reason} | calls: ${calls}`);
  }

  try {
    await limitedMap(["x"], async value => value, 0, new AbortController().signal);
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  }
}

main();
Hint 1: the idea

Each worker is a loop that takes the next unclaimed index before it awaits, so two workers can never take the same item, and a worker that finishes immediately loops round to claim another. Both checks (limit and signal) belong before the first worker starts.

Hint 2: a first step

Replace the Promise.all(values.map(...)) line with a next counter, an async function worker() that loops while (next < values.length), and two workers started with Array.from. Run it: the first three lines should now be right. Then add the two checks at the top.

Show one solution
JavaScript
async function main() {
  async function limitedMap(values, mapper, limit, signal) {
    if (!Number.isInteger(limit) || limit < 1) {
      throw new RangeError("limit must be a positive integer");
    }
    signal.throwIfAborted();

    let next = 0;
    const results = [];

    async function worker() {
      while (next < values.length) {
        const index = next++;
        results[index] = await mapper(values[index], index);
      }
    }

    const workers = Array.from({ length: Math.min(limit, values.length) }, () => worker());
    await Promise.all(workers);
    return results;
  }

  // ---- test harness: each call waits until the test releases it ----
  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }
  const tick = () => new Promise(resolve => setTimeout(resolve, 0));

  const gates = [];
  const started = [];
  let active = 0;
  let peak = 0;

  async function mapper(value, index) {
    started.push(index);
    active += 1;
    peak = Math.max(peak, active);
    gates[index] = deferred();
    await gates[index].promise;
    active -= 1;
    return value.toUpperCase();
  }

  const run = limitedMap(["a", "b", "c", "d"], mapper, 2, new AbortController().signal);
  await tick();
  console.log(`started: ${started.join(",")}`);

  gates[1].resolve();
  await tick();
  console.log(`after releasing 1: ${started.join(",")}`);

  gates[0].resolve();
  await tick();
  gates[2].resolve();
  gates[3].resolve();
  console.log(`results: ${(await run).join(",")} | peak: ${peak}`);

  const stopped = new AbortController();
  stopped.abort("not needed");
  let calls = 0;
  try {
    await limitedMap(["x"], async () => calls++, 2, stopped.signal);
  } catch (reason) {
    console.log(`pre-aborted: ${reason} | calls: ${calls}`);
  }

  try {
    await limitedMap(["x"], async value => value, 0, new AbortController().signal);
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  }
}

main();
Text
started: 0,1
after releasing 1: 0,1,2
results: A,B,C,D | peak: 2
pre-aborted: not needed | calls: 0
RangeError: limit must be a positive integer

Only two workers exist, so at most two calls can be active: the harness measures a peak of 2. When call 1 is released, the worker that ran it loops and claims index 2 straight away, while call 0 is still held; a batch version would print 0,1 on that line. results[index] = writes each value to the slot its worker claimed before awaiting, so the out-of-order releases still give A,B,C,D. throwIfAborted() and the limit check both run before Array.from starts any worker, which is why the pre-aborted run makes 0 calls and limit 0 throws before calling the mapper. Math.min(limit, values.length) avoids starting idle workers for short input.

Change it and test it

Make one mutation at a time and name the line of output that catches it: replace results[index] = with results.push(...); move signal.throwIfAborted() below the worker start; start limit + 1 workers. Then rewrite limitedMap as batches with Promise.all on slices and see which line changes.

Was this article helpful?

Your response is saved on this device.