This lesson is optional. Everything else in the course runs in the page. Do it if you want to run the real project and its test suite on your own computer.
JavaScript intermediate taught ES modules. In this download, map-limit.js exports mapLimit and TaskError; main.js imports the public function and demonstrates its output. package.json has type:module so Node treats .js files as ES modules. There are no dependencies, so there is nothing to npm install.
Set up Node 22 and run the project
-
Check whether Node is installed, and which version, by running this in a terminal:
Shellnode --versionYou need
v22or later. If the command is not found or prints an older version, install the current LTS release from nodejs.org, then open a new terminal and check again.npmcomes with Node. -
Extract task-pool.zip and move into the folder:
cd task-pool. -
Run
npm start. It should print30,10,20. -
Run
npm test. In a terminal, the end of the report looks like this (the durations differ):
✔ bounded starts, ordered results despite out-of-order completion
✔ first failure stops pulling and waits for active work
✔ pre-abort starts no jobs; mid-flight abort preserves reason and closes source
✔ invalid limits, empty sources and iterator failures
✔ cleanup failure does not replace a task failure; thrown undefined is still failure
✔ external abort listener is released on success and failure
ℹ tests 6
ℹ pass 6
ℹ fail 0If npm start reports Cannot use import statement outside a module, you are not in the folder containing package.json. If it reports an unknown throwIfAborted or a syntax error in map-limit.js, your Node is older than 22.
These are shell commands, not statements to paste into a console editor.
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.
// Two "modules" written as functions so they fit in one editor.
// totals.js would export sum; main.js would import it.
function totalsModule() {
const sum = values => values.reduce((total, n) => total + n, 0);
const secret = "not exported";
return { sum };
}
const imported = totalsModule();
console.log(imported.sum([3, 1, 2]));
console.log(Object.keys(imported).join(","));
console.log(imported.secret);Check your prediction
6
sum
undefinedA module's exports are the only names a caller can reach. secret exists inside the module but was never exported, just as TaskError's helpers inside map-limit.js are invisible to main.js unless exported. In a real module, importing a name that is not exported is an error when the module graph loads, not undefined.
Follow source, entry point and tests separately
Open map-limit.js for the library contract, main.js for one caller and pool.test.js for controlled schedules. The demo chooses input and prints results; the library owns concurrency and cleanup. A successful demo is not evidence for every schedule. Keep its entry convention separate from the browser editor: Node ES modules can await at top level, while the classic-script editor uses async main followed by main().
| Boundary or case | What to inspect |
|---|---|
| Demo | Expect ordered output without a live service |
| Tests | Inspect a held callback and source finally fixture |
| Edits | Keep source, combined listing and archive synchronized |
Change only a demo input and predict its new result. Then identify the exported-function test catching a completion-order implementation. Keep generated output and dependencies outside authored source and rebuild the public archive after source edits.
Your turn
Write the caller main.js needs
A caller of mapLimit decides how failures are reported. Write loadTitles(ids, fetchTitle, signal), the kind of function a real main.js would import and use. It loads titles with limit 2. A TaskError becomes <id> failed: <message>, using the error's index to find the id, so the person reading the message never sees "Task 1". The caller's own abort becomes stopped: <reason>. Anything else, such as a caller passing something that is not a signal, is a bug and must still throw. The full pool is included above loadTitles. Print:
loaded: Loops, Closures, Generators
c3 failed: not found
stopped: user left
caller bug surfaces: TypeErrorasync 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;
}
// ---- main.js-style caller code ----
async function loadTitles(ids, fetchTitle, signal) {
// Call mapLimit with limit 2. Turn a TaskError into "<id> failed: <message>"
// and the caller's own abort into "stopped: <reason>". Let anything else throw.
try {
const titles = await mapLimit(ids, id => fetchTitle(id), { limit: 2, signal });
return `loaded: ${titles.join(", ")}`;
} catch (error) {
return `failed: ${error}`;
}
}
const catalogue = { c1: "Loops", c2: "Closures", c4: "Generators" };
const fetchTitle = async id => {
if (!(id in catalogue)) throw new Error("not found");
return catalogue[id];
};
console.log(await loadTitles(["c1", "c2", "c4"], fetchTitle));
console.log(await loadTitles(["c1", "c3", "c4"], fetchTitle));
const leaving = new AbortController();
leaving.abort("user left");
console.log(await loadTitles(["c1"], fetchTitle, leaving.signal));
try {
await loadTitles(["c1"], fetchTitle, "not a signal");
} catch (error) {
console.log(`caller bug surfaces: ${error.name}`);
}
}
main();Hint 1: the idea
The pool already gives you everything you need to tell the failures apart: a TaskError carries index and cause, an abort rejects with exactly signal.reason, and argument mistakes throw a TypeError or RangeError. The catch block's job is to translate only the first two.
Hint 2: a first step
Run the starter: the second line prints failed: TaskError: Task 1 failed, which tells the reader nothing about which id or why. Start with an instanceof TaskError branch that uses ids[error.index] and error.cause.message. Then handle the abort, and rethrow everything else.
Show one solution
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;
}
// ---- main.js-style caller code ----
async function loadTitles(ids, fetchTitle, signal) {
try {
const titles = await mapLimit(ids, id => fetchTitle(id), { limit: 2, signal });
return `loaded: ${titles.join(", ")}`;
} catch (error) {
if (error instanceof TaskError) {
return `${ids[error.index]} failed: ${error.cause.message}`;
}
if (signal?.aborted && error === signal.reason) {
return `stopped: ${error}`;
}
throw error;
}
}
const catalogue = { c1: "Loops", c2: "Closures", c4: "Generators" };
const fetchTitle = async id => {
if (!(id in catalogue)) throw new Error("not found");
return catalogue[id];
};
console.log(await loadTitles(["c1", "c2", "c4"], fetchTitle));
console.log(await loadTitles(["c1", "c3", "c4"], fetchTitle));
const leaving = new AbortController();
leaving.abort("user left");
console.log(await loadTitles(["c1"], fetchTitle, leaving.signal));
try {
await loadTitles(["c1"], fetchTitle, "not a signal");
} catch (error) {
console.log(`caller bug surfaces: ${error.name}`);
}
}
main();loaded: Loops, Closures, Generators
c3 failed: not found
stopped: user left
caller bug surfaces: TypeErrorerror.index is the position the pool assigned when it pulled the item, so ids[error.index] is the id whose fetch failed, and error.cause is that fetch's own Error. The abort branch compares the rejection with signal.reason by identity, because the pool passes the caller's reason through unchanged: the string "user left". The final throw error matters as much as the two translations. Passing "not a signal" is a mistake in the calling code, and swallowing its TypeError into a friendly message would hide that bug. In the downloaded project, this function would live in its own module, export loadTitles, and import mapLimit and TaskError from map-limit.js.
Change it and test it
If you ran the project, move loadTitles into its own file, load-titles.js, export it, and import it from main.js. Then change only main.js to use limit 1. Keep tests intact. Explain how you would tell a caller about finite-input and retained-output limits before they try a huge or infinite source.
Completion is saved in this browser only. It does not measure mastery.