A library can have only two active jobs and still allocate a million queued promises. Bound the work that is started and inspect how inputs are obtained. A synchronous iterator lets the consumer pull the next item when capacity exists instead of first spreading the source into an array.
This is a form of demand control: the consumer asks for more work at its own pace. It is not a complete streaming system. A result array retained until the end still grows with total input, and a source that eagerly allocated everything has already used that memory.
For early exit, close an unfinished iterator. A small take helper can express a bounded view of a source; it must not pull an extra item merely to discover that the quota has been reached. A for...of loop that checks the limit inside its body has already fetched the next item; the example below shows that extra read. Check demand before next().
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.
let reads = 0;
function* source() {
for (let n = 0; n < 5; n++) {
reads++;
yield n;
}
}
const iterator = source();
const pair = [iterator.next().value, iterator.next().value];
console.log(pair.join(","));
console.log(reads);
iterator.return();Check your prediction
0,1
2Read iterator.return?.() as “call return if that method is present.” This is the method-call form of the optional chaining you already used for properties. Some iterators have no return method. For a generator, calling return enters its finally block and closes unfinished iteration.
Count pulls at the source boundary
A limit on active mapper calls does not automatically limit queued promises or input reads. Count next calls at the source to see whether the consumer asks for values it has no capacity to process. Demand checks should precede the next pull.
A zero quota is especially revealing: the consumer should not need one value merely to discover that it wants none. Early closure and normal exhaustion are distinct states; close an unfinished owned iterator without inventing an extra read to detect its end.
let reads = 0;
function* source() {
for (let n = 0; n < 4; n++) {
reads++;
yield n;
}
}
const cursor = source();
console.log(reads);
cursor.next();
cursor.next();
console.log(reads);
cursor.return();Check your prediction
0
2Creating the generator performs no pulls. The two explicit next calls are the only demand in this example. Instrument the boundary rather than guessing from output count.
let reads = 0;
function* source() {
reads++;
yield 1;
}
const cursor = source();
const quota = 0;
for (let n = 0; n < quota; n++) {
cursor.next();
}
cursor.return();
console.log(reads);Check your prediction
0The source body was never entered. Closing an unstarted generator also does not run its body’s finally block; resources must be acquired inside the lifetime you can actually observe.
Try the rule on new inputs
Test quotas zero, one, exactly the source length and larger than the source. Keep separate counters for pulls and mapper calls. Explain why returning a collected result array still needs memory proportional to output size.
See the extra read
The difference between "check, then pull" and "pull, then check" is invisible in the returned values, so this example logs every next() and return() on a hand-written source. counted(limit, log) is its own iterator: its [Symbol.iterator]() returns this. Predict the three log lines.
function counted(limit, log) {
let n = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
if (n >= limit) return { value: undefined, done: true };
log.push(`read ${n}`);
return { value: n++, done: false };
},
return() {
log.push("closed");
return { value: undefined, done: true };
}
};
}
function takeAfterPull(values, count) {
const out = [];
for (const value of values) {
if (out.length === count) break;
out.push(value);
}
return out;
}
function takeBeforePull(values, count) {
const iterator = values[Symbol.iterator]();
const out = [];
let exhausted = false;
try {
while (out.length < count) {
const step = iterator.next();
if (step.done) {
exhausted = true;
break;
}
out.push(step.value);
}
} finally {
if (!exhausted) iterator.return?.();
}
return out;
}
const a = [];
console.log(takeAfterPull(counted(5, a), 2).join(","), "|", a.join(", "));
const b = [];
console.log(takeBeforePull(counted(5, b), 2).join(","), "|", b.join(", "));
const c = [];
console.log(takeBeforePull(counted(1, c), 3).join(","), "|", c.join(", "));Check your prediction
0,1 | read 0, read 1, read 2, closed
0,1 | read 0, read 1, closed
0 | read 0takeAfterPull looks right and returns the right values, but for...of has already called next() for item 2 before the body discovers it is full: three reads for two results. If reading claims a job or a network page, that third item is lost. takeBeforePull asks "is there room?" in the while condition, so next() is only called when the value will be kept. Its finally closes the iterator when it stops early, but not in the third case, where the source ran out on its own: an exhausted iterator has nothing to release. (The generator take from the lazy-pipelines lesson avoids the extra read differently: it checks the count right after yield, before its loop asks for more.)
Trace the contract before building
An active-job limit and a queued-memory limit are different promises. Prebuilding a promise or wrapper for every source item can retain the entire workload even if only two mappers run at once. A pull-based source lets the consumer decide when to request another value.
Trace next calls as a resource budget. A helper that checks its quota only after pulling may request one item too many, which can matter when pulling has effects or owns resources. The pool's result array still grows with total output; its bounded starts are not a claim that every aspect of memory is constant.
Your turn
Zip two sources without over-reading
Write zip(left, right), which pairs items from two iterables into strings like "a1" until either one runs out. Pull from left first, then right. Two rules: never call next() on right when left has just finished, and when you stop, call return() on each iterator that did not finish by itself (and only on those). The supplied source logs every read, every done and every return(). Print:
a1 b2
L a, R 1, L b, R 2, L c, R done, L closed
a1
L a, R 1, L done, R closedfunction source(name, items, log) {
let index = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
if (index >= items.length) {
log.push(`${name} done`);
return { value: undefined, done: true };
}
log.push(`${name} ${items[index]}`);
return { value: items[index++], done: false };
},
return() {
log.push(`${name} closed`);
return { value: undefined, done: true };
}
};
}
function zip(left, right) {
// Pull one from left, then one from right, until either is done.
// Close (return) only the iterators that did not finish by themselves.
return [];
}
const log1 = [];
console.log(zip(source("L", ["a", "b", "c"], log1), source("R", [1, 2], log1)).join(" "));
console.log(log1.join(", "));
const log2 = [];
console.log(zip(source("L", ["a"], log2), source("R", [1, 2, 3], log2)).join(" "));
console.log(log2.join(", "));Hint 1: the idea
There are now two iterators and each can end in one of two ways: it reported done itself, or you stopped using it while it still had items. Keep one flag per iterator, and let a single finally close whichever ones are unfinished.
Hint 2: a first step
Start with the while (true) loop that pulls a.next(), breaks if it is done, then pulls b.next(). Leave out finally. Run it: the pairs are right, but nothing is ever closed. Then add the two flags.
Show one solution
function source(name, items, log) {
let index = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
if (index >= items.length) {
log.push(`${name} done`);
return { value: undefined, done: true };
}
log.push(`${name} ${items[index]}`);
return { value: items[index++], done: false };
},
return() {
log.push(`${name} closed`);
return { value: undefined, done: true };
}
};
}
function zip(left, right) {
const a = left[Symbol.iterator]();
const b = right[Symbol.iterator]();
let aDone = false;
let bDone = false;
const pairs = [];
try {
while (true) {
const x = a.next();
if (x.done) {
aDone = true;
break;
}
const y = b.next();
if (y.done) {
bDone = true;
break;
}
pairs.push(`${x.value}${y.value}`);
}
} finally {
if (!aDone) a.return?.();
if (!bDone) b.return?.();
}
return pairs;
}
const log1 = [];
console.log(zip(source("L", ["a", "b", "c"], log1), source("R", [1, 2], log1)).join(" "));
console.log(log1.join(", "));
const log2 = [];
console.log(zip(source("L", ["a"], log2), source("R", [1, 2, 3], log2)).join(" "));
console.log(log2.join(", "));a1 b2
L a, R 1, L b, R 2, L c, R done, L closed
a1
L a, R 1, L done, R closedIn the first run R runs out first: zip has already read c from L, which cannot be avoided because L is pulled first, then sees R done, so R is not closed but L, still holding an item, is. In the second run L is done, so the loop breaks before touching R again; R has items left and gets R closed, while L does not. The flags are what stop zip from calling return() on an iterator that already finished. This is the same "close only what you did not exhaust" rule as takeBeforePull, applied once per source.
Change it and test it
Rewrite takeBeforePull as a generator and test count zero, an empty source and a quota larger than the source. Explain why collecting every output from a bounded pool still needs O(n) memory; active concurrency and total memory are different quantities.
Completion is saved in this browser only. It does not measure mastery.