Skip to content

Capstone: Ordered Task Pool

The Course
•
25 min study

The complete library connects the week's contracts. It obtains one synchronous iterator, starts a bounded number of worker loops, assigns each item an index before awaiting, and writes results at that index. It stops pulling once a failure is observed.

Each invocation owns an internal AbortController. External cancellation or the first mapper failure aborts peers, but the library awaits active callbacks before settling. It therefore depends on callbacks eventually settling. TaskError preserves the mapper index and cause; source errors and external abort reasons follow their documented policies.

Read the failed flag independently of failure's value. Notice cleanup in finally: remove the external listener and close an unfinished iterator. A cleanup failure does not overwrite a primary error. This is a finite-input, collected-output API, not an async-iterable or streaming-output system.

Download the project to inspect the real modules and controlled-schedule tests. The long example below is the same implementation combined into one editor; it needs no account or network service.

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() {
  /** A synchronous iterable, async mapper, bounded active calls, ordered results.
   * Stop pulling on the first observed failure; cooperatively abort peers, then
   * wait for active callbacks before rejecting. Callbacks must settle themselves.
   */
  class TaskError extends Error {
    constructor(index, cause) {
      super(`Task ${index} failed`, { cause });
      this.name = "TaskError";
      this.index = index;
    }
  }

  async function mapLimit(items, mapper, { limit = 2, signal } = {}) {
    if (!Number.isInteger(limit) || limit < 1 || limit > 64) {
      throw new RangeError("limit must be an integer from 1 to 64");
    }

    if (typeof mapper !== "function") {
      throw new TypeError("mapper must be a function");
    }

    if (typeof items?.[Symbol.iterator] !== "function") {
      throw new TypeError("Expected an iterable");
    }

    if (signal !== undefined && !(signal instanceof AbortSignal)) {
      throw new TypeError("Expected an AbortSignal");
    }

    signal?.throwIfAborted();

    const iterator = items[Symbol.iterator]();
    const controller = new AbortController();
    const results = [];
    let nextIndex = 0;
    let exhausted = false;
    let failed = false;
    let failure;
    const fail = error => {
      if (failed) {
        return;
      }

      failed = true;
      failure = error;
      controller.abort(error);
    };
    const onAbort = () => fail(signal.reason);

    signal?.addEventListener("abort", onAbort, { once: true });

    // A custom iterable may have triggered an abort during iterator creation.
    if (signal?.aborted) {
      onAbort();
    }

    async function worker() {
      while (!failed && !exhausted) {
        let step;

        try {
          step = iterator.next();

          if (
            step === null ||
            (typeof step !== "object" && typeof step !== "function")
          ) {
            throw new TypeError("Iterator result must be an object");
          }
        } catch (error) {
          fail(error);
          return;
        }

        if (step.done) {
          exhausted = true;
          return;
        }

        if (failed) {
          return;
        }

        const index = nextIndex++;

        try {
          results[index] = await mapper(step.value, index, controller.signal);
        } catch (error) {
          fail(new TaskError(index, error));
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      signal?.removeEventListener("abort", onAbort);

      if (!exhausted) {
        try {
          iterator.return?.();
        } catch (error) {
          if (!failed) {
            fail(error);
          }
        }
      }
    }

    if (failed) {
      throw failure;
    }

    return results;
  }

  console.log(
    (await mapLimit([3, 1, 2], async value => value * 10, { limit: 2 })).join(
      ","
    )
  );
}

main();
Check your prediction
Text
30,10,20

Read the pool as four collaborating phases

Trace one input through validation, source consumption, callback execution and cleanup instead of memorizing the listing. Keep input index, active-call count and failure state in separate columns. The worker reserves an index before awaiting and writes the result there. After failure, it stops new pulls while the outer operation still waits for active callbacks to settle.

Boundary or caseWhat to inspect
InvocationValidate limit, mapper, source and optional signal
WorkerPull with capacity and reserve the result position before await
SettlementPreserve primary failure and release listener and unfinished iterator

Use three inputs with visibly different outputs. Follow ordinary completion, then the controlled reverse-completion test. Identify the exact point new work stops after failure and which already active callback must still settle before rejection.

Drive the pool through failure and cancellation

The first run only showed the happy path. These two runs use the same mapLimit, repeated in each editor because every editor runs on its own. Predict each one before running it.

A held job and a failure JavaScript
async function main() {
  /** A synchronous iterable, async mapper, bounded active calls, ordered results.
   * Stop pulling on the first observed failure; cooperatively abort peers, then
   * wait for active callbacks before rejecting. Callbacks must settle themselves.
   */
  class TaskError extends Error {
    constructor(index, cause) {
      super(`Task ${index} failed`, { cause });
      this.name = "TaskError";
      this.index = index;
    }
  }

  async function mapLimit(items, mapper, { limit = 2, signal } = {}) {
    if (!Number.isInteger(limit) || limit < 1 || limit > 64) {
      throw new RangeError("limit must be an integer from 1 to 64");
    }

    if (typeof mapper !== "function") {
      throw new TypeError("mapper must be a function");
    }

    if (typeof items?.[Symbol.iterator] !== "function") {
      throw new TypeError("Expected an iterable");
    }

    if (signal !== undefined && !(signal instanceof AbortSignal)) {
      throw new TypeError("Expected an AbortSignal");
    }

    signal?.throwIfAborted();

    const iterator = items[Symbol.iterator]();
    const controller = new AbortController();
    const results = [];
    let nextIndex = 0;
    let exhausted = false;
    let failed = false;
    let failure;
    const fail = error => {
      if (failed) {
        return;
      }

      failed = true;
      failure = error;
      controller.abort(error);
    };
    const onAbort = () => fail(signal.reason);

    signal?.addEventListener("abort", onAbort, { once: true });

    // A custom iterable may have triggered an abort during iterator creation.
    if (signal?.aborted) {
      onAbort();
    }

    async function worker() {
      while (!failed && !exhausted) {
        let step;

        try {
          step = iterator.next();

          if (
            step === null ||
            (typeof step !== "object" && typeof step !== "function")
          ) {
            throw new TypeError("Iterator result must be an object");
          }
        } catch (error) {
          fail(error);
          return;
        }

        if (step.done) {
          exhausted = true;
          return;
        }

        if (failed) {
          return;
        }

        const index = nextIndex++;

        try {
          results[index] = await mapper(step.value, index, controller.signal);
        } catch (error) {
          fail(new TaskError(index, error));
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      signal?.removeEventListener("abort", onAbort);

      if (!exhausted) {
        try {
          iterator.return?.();
        } catch (error) {
          if (!failed) {
            fail(error);
          }
        }
      }
    }

    if (failed) {
      throw failure;
    }

    return results;
  }


  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }

  const started = [];
  const held = deferred();
  const outer = mapLimit(
    ["a", "b", "c"],
    async (value, index, signal) => {
      started.push(value);
      if (value === "a") {
        signal.addEventListener("abort", () => started.push("a saw abort"));
        await held.promise; // ignores the signal
        return "A";
      }
      if (value === "b") throw new Error("b broke");
      return value.toUpperCase();
    },
    { limit: 2 }
  );

  let settled = false;
  outer.then(
    () => (settled = true),
    () => (settled = true)
  );
  await new Promise(resolve => setTimeout(resolve, 0));
  console.log(`before release: ${started.join(", ")} | settled ${settled}`);

  held.resolve();
  try {
    await outer;
  } catch (error) {
    console.log(`${error.name} index ${error.index}: ${error.cause.message}`);
  }
}

main();
Check your prediction
Text
before release: a, b, a saw abort | settled false
TaskError index 1: b broke

With limit 2, the pool starts a and b. b rejects, so the pool records TaskError(1, ...), aborts its controller (that is when a sees the abort) and stops pulling: c never starts. a ignores the signal, so the settled flag is still false after a full timer turn: the pool is waiting for its active callback, exactly as its comment promises. Only after the test releases a does mapLimit reject, and it rejects with the first failure it observed, b's. a's late success is not added to anything.

Already aborted JavaScript
async function main() {
  /** A synchronous iterable, async mapper, bounded active calls, ordered results.
   * Stop pulling on the first observed failure; cooperatively abort peers, then
   * wait for active callbacks before rejecting. Callbacks must settle themselves.
   */
  class TaskError extends Error {
    constructor(index, cause) {
      super(`Task ${index} failed`, { cause });
      this.name = "TaskError";
      this.index = index;
    }
  }

  async function mapLimit(items, mapper, { limit = 2, signal } = {}) {
    if (!Number.isInteger(limit) || limit < 1 || limit > 64) {
      throw new RangeError("limit must be an integer from 1 to 64");
    }

    if (typeof mapper !== "function") {
      throw new TypeError("mapper must be a function");
    }

    if (typeof items?.[Symbol.iterator] !== "function") {
      throw new TypeError("Expected an iterable");
    }

    if (signal !== undefined && !(signal instanceof AbortSignal)) {
      throw new TypeError("Expected an AbortSignal");
    }

    signal?.throwIfAborted();

    const iterator = items[Symbol.iterator]();
    const controller = new AbortController();
    const results = [];
    let nextIndex = 0;
    let exhausted = false;
    let failed = false;
    let failure;
    const fail = error => {
      if (failed) {
        return;
      }

      failed = true;
      failure = error;
      controller.abort(error);
    };
    const onAbort = () => fail(signal.reason);

    signal?.addEventListener("abort", onAbort, { once: true });

    // A custom iterable may have triggered an abort during iterator creation.
    if (signal?.aborted) {
      onAbort();
    }

    async function worker() {
      while (!failed && !exhausted) {
        let step;

        try {
          step = iterator.next();

          if (
            step === null ||
            (typeof step !== "object" && typeof step !== "function")
          ) {
            throw new TypeError("Iterator result must be an object");
          }
        } catch (error) {
          fail(error);
          return;
        }

        if (step.done) {
          exhausted = true;
          return;
        }

        if (failed) {
          return;
        }

        const index = nextIndex++;

        try {
          results[index] = await mapper(step.value, index, controller.signal);
        } catch (error) {
          fail(new TaskError(index, error));
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      signal?.removeEventListener("abort", onAbort);

      if (!exhausted) {
        try {
          iterator.return?.();
        } catch (error) {
          if (!failed) {
            fail(error);
          }
        }
      }
    }

    if (failed) {
      throw failure;
    }

    return results;
  }


  const controller = new AbortController();
  controller.abort("cancelled");

  let iteratorCreated = false;
  let calls = 0;
  const source = {
    [Symbol.iterator]() {
      iteratorCreated = true;
      return [1, 2, 3][Symbol.iterator]();
    }
  };

  try {
    await mapLimit(source, async value => {
      calls += 1;
      return value;
    }, { signal: controller.signal });
  } catch (reason) {
    console.log(`rejected with: ${reason}`);
  }
  console.log(`iterator created: ${iteratorCreated} | mapper calls: ${calls}`);
}

main();
Check your prediction
Text
rejected with: cancelled
iterator created: false | mapper calls: 0

signal?.throwIfAborted() runs after the argument checks but before items[Symbol.iterator](), so a pre-aborted call rejects with the signal's own reason ("cancelled", a string, passed through unchanged) without creating an iterator or calling the mapper. Moving that check below the iterator creation would still reject, but would first run the source's own setup code.

Your turn

Exercise

Add an onStart hook to the pool

Change the pool above (it is repeated in the workspace) to accept an optional onStart(index, value) callback in its options. It runs once for each item, just before that item's mapper call. Acceptance cases:

  • it reports every started item once, in index order;
  • items that never start because of an earlier failure are never reported;
  • if onStart throws, that counts as the item's failure (a TaskError with that index) and its mapper does not run;
  • a non-function onStart is a TypeError, raised before any work starts.

The four checks are at the bottom of the workspace. Print:

Text
ordinary: 30,10,20
  starts 0:3 1:1 2:2
failure: TaskError index 1 (b broke)
  starts 0 1
hook throws: TaskError index 1 (hook refused)
  mapper ran for x
bad hook: TypeError: onStart must be a function
Your workspace JavaScript
async function main() {
  /** A synchronous iterable, async mapper, bounded active calls, ordered results.
   * Stop pulling on the first observed failure; cooperatively abort peers, then
   * wait for active callbacks before rejecting. Callbacks must settle themselves.
   */
  class TaskError extends Error {
    constructor(index, cause) {
      super(`Task ${index} failed`, { cause });
      this.name = "TaskError";
      this.index = index;
    }
  }

  async function mapLimit(items, mapper, { limit = 2, signal } = {}) {
    if (!Number.isInteger(limit) || limit < 1 || limit > 64) {
      throw new RangeError("limit must be an integer from 1 to 64");
    }

    if (typeof mapper !== "function") {
      throw new TypeError("mapper must be a function");
    }

    if (typeof items?.[Symbol.iterator] !== "function") {
      throw new TypeError("Expected an iterable");
    }

    if (signal !== undefined && !(signal instanceof AbortSignal)) {
      throw new TypeError("Expected an AbortSignal");
    }

    signal?.throwIfAborted();

    const iterator = items[Symbol.iterator]();
    const controller = new AbortController();
    const results = [];
    let nextIndex = 0;
    let exhausted = false;
    let failed = false;
    let failure;
    const fail = error => {
      if (failed) {
        return;
      }

      failed = true;
      failure = error;
      controller.abort(error);
    };
    const onAbort = () => fail(signal.reason);

    signal?.addEventListener("abort", onAbort, { once: true });

    // A custom iterable may have triggered an abort during iterator creation.
    if (signal?.aborted) {
      onAbort();
    }

    async function worker() {
      while (!failed && !exhausted) {
        let step;

        try {
          step = iterator.next();

          if (
            step === null ||
            (typeof step !== "object" && typeof step !== "function")
          ) {
            throw new TypeError("Iterator result must be an object");
          }
        } catch (error) {
          fail(error);
          return;
        }

        if (step.done) {
          exhausted = true;
          return;
        }

        if (failed) {
          return;
        }

        const index = nextIndex++;

        try {
          results[index] = await mapper(step.value, index, controller.signal);
        } catch (error) {
          fail(new TaskError(index, error));
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      signal?.removeEventListener("abort", onAbort);

      if (!exhausted) {
        try {
          iterator.return?.();
        } catch (error) {
          if (!failed) {
            fail(error);
          }
        }
      }
    }

    if (failed) {
      throw failure;
    }

    return results;
  }


  async function attempt(label, run) {
    try {
      console.log(`${label}: ${(await run()).join(",")}`);
    } catch (error) {
      const detail = error instanceof TaskError ? ` index ${error.index} (${error.cause.message})` : `: ${error.message}`;
      console.log(`${label}: ${error.name}${detail}`);
    }
  }

  // 1. Every started item is reported once, in index order.
  const starts = [];
  await attempt("ordinary", () =>
    mapLimit([3, 1, 2], async value => value * 10, {
      limit: 2,
      onStart: (index, value) => starts.push(`${index}:${value}`)
    })
  );
  console.log(`  starts ${starts.join(" ")}`);

  // 2. After a failure, items that never start are never reported.
  const afterFailure = [];
  await attempt("failure", () =>
    mapLimit(["a", "b", "c"], async value => {
      if (value === "b") throw new Error("b broke");
      return value;
    }, { limit: 1, onStart: index => afterFailure.push(index) })
  );
  console.log(`  starts ${afterFailure.join(" ")}`);

  // 3. A throwing hook is that task's failure; its mapper never runs.
  const mapped = [];
  await attempt("hook throws", () =>
    mapLimit(["x", "y"], async value => {
      mapped.push(value);
      return value;
    }, {
      limit: 1,
      onStart: index => {
        if (index === 1) throw new Error("hook refused");
      }
    })
  );
  console.log(`  mapper ran for ${mapped.join(",")}`);

  // 4. A hook that is not a function is rejected before any work.
  await attempt("bad hook", () => mapLimit([1], async v => v, { onStart: "yes" }));
}

main();
Hint 1: the idea

Each acceptance case points at a phase of the pool from the table above: validation happens before the iterator is created, and the worker already has one place where a failure is turned into TaskError(index, ...). A hook that must count as the task's failure belongs where that conversion already happens.

Hint 2: a first step

Run the workspace unchanged first: the pool ignores the unknown option, so starts stays empty and hook throws succeeds. Add onStart to the destructured options and add a type check next to the existing ones, then run again: only bad hook changes. The remaining work is one line in worker, after the index is reserved.

Show one solution
JavaScript
async function main() {
  /** A synchronous iterable, async mapper, bounded active calls, ordered results.
   * Stop pulling on the first observed failure; cooperatively abort peers, then
   * wait for active callbacks before rejecting. Callbacks must settle themselves.
   */
  class TaskError extends Error {
    constructor(index, cause) {
      super(`Task ${index} failed`, { cause });
      this.name = "TaskError";
      this.index = index;
    }
  }

  async function mapLimit(items, mapper, { limit = 2, signal, onStart } = {}) {
    if (!Number.isInteger(limit) || limit < 1 || limit > 64) {
      throw new RangeError("limit must be an integer from 1 to 64");
    }

    if (typeof mapper !== "function") {
      throw new TypeError("mapper must be a function");
    }

    if (typeof items?.[Symbol.iterator] !== "function") {
      throw new TypeError("Expected an iterable");
    }

    if (onStart !== undefined && typeof onStart !== "function") {
      throw new TypeError("onStart must be a function");
    }

    if (signal !== undefined && !(signal instanceof AbortSignal)) {
      throw new TypeError("Expected an AbortSignal");
    }

    signal?.throwIfAborted();

    const iterator = items[Symbol.iterator]();
    const controller = new AbortController();
    const results = [];
    let nextIndex = 0;
    let exhausted = false;
    let failed = false;
    let failure;
    const fail = error => {
      if (failed) {
        return;
      }

      failed = true;
      failure = error;
      controller.abort(error);
    };
    const onAbort = () => fail(signal.reason);

    signal?.addEventListener("abort", onAbort, { once: true });

    // A custom iterable may have triggered an abort during iterator creation.
    if (signal?.aborted) {
      onAbort();
    }

    async function worker() {
      while (!failed && !exhausted) {
        let step;

        try {
          step = iterator.next();

          if (
            step === null ||
            (typeof step !== "object" && typeof step !== "function")
          ) {
            throw new TypeError("Iterator result must be an object");
          }
        } catch (error) {
          fail(error);
          return;
        }

        if (step.done) {
          exhausted = true;
          return;
        }

        if (failed) {
          return;
        }

        const index = nextIndex++;

        try {
          onStart?.(index, step.value);
          results[index] = await mapper(step.value, index, controller.signal);
        } catch (error) {
          fail(new TaskError(index, error));
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      signal?.removeEventListener("abort", onAbort);

      if (!exhausted) {
        try {
          iterator.return?.();
        } catch (error) {
          if (!failed) {
            fail(error);
          }
        }
      }
    }

    if (failed) {
      throw failure;
    }

    return results;
  }


  async function attempt(label, run) {
    try {
      console.log(`${label}: ${(await run()).join(",")}`);
    } catch (error) {
      const detail = error instanceof TaskError ? ` index ${error.index} (${error.cause.message})` : `: ${error.message}`;
      console.log(`${label}: ${error.name}${detail}`);
    }
  }

  // 1. Every started item is reported once, in index order.
  const starts = [];
  await attempt("ordinary", () =>
    mapLimit([3, 1, 2], async value => value * 10, {
      limit: 2,
      onStart: (index, value) => starts.push(`${index}:${value}`)
    })
  );
  console.log(`  starts ${starts.join(" ")}`);

  // 2. After a failure, items that never start are never reported.
  const afterFailure = [];
  await attempt("failure", () =>
    mapLimit(["a", "b", "c"], async value => {
      if (value === "b") throw new Error("b broke");
      return value;
    }, { limit: 1, onStart: index => afterFailure.push(index) })
  );
  console.log(`  starts ${afterFailure.join(" ")}`);

  // 3. A throwing hook is that task's failure; its mapper never runs.
  const mapped = [];
  await attempt("hook throws", () =>
    mapLimit(["x", "y"], async value => {
      mapped.push(value);
      return value;
    }, {
      limit: 1,
      onStart: index => {
        if (index === 1) throw new Error("hook refused");
      }
    })
  );
  console.log(`  mapper ran for ${mapped.join(",")}`);

  // 4. A hook that is not a function is rejected before any work.
  await attempt("bad hook", () => mapLimit([1], async v => v, { onStart: "yes" }));
}

main();
Text
ordinary: 30,10,20
  starts 0:3 1:1 2:2
failure: TaskError index 1 (b broke)
  starts 0 1
hook throws: TaskError index 1 (hook refused)
  mapper ran for x
bad hook: TypeError: onStart must be a function

The type check sits with the other validations, before signal?.throwIfAborted() and before the iterator exists, so a bad hook starts no work. The call onStart?.(index, step.value) goes inside the try that already wraps the mapper, after nextIndex++. That position gives every acceptance case at once. The index is final, so reports come in index order. Nothing is reported for an item that was never pulled, because a failure stops the loop before the next iterator.next(). And a throwing hook skips the await mapper(...) on the next line and lands in the existing catch, which wraps it as TaskError(1, ...). Putting the call before the try instead would make worker itself reject. Promise.all would then reject at once with the raw hook error, not a TaskError, and the pool would settle without waiting for its other active callbacks.

Change it and test it

Add a fifth case: an external signal aborted while a job is held. Predict whether onStart is called for any item after the abort, then check. List the callback assumptions the pool still makes, such as callbacks eventually settling, that no option you add can remove.

Was this article helpful?

Your response is saved on this device.