JavaScriptFundamental (ES6), part 1
Symbol.asyncIterator for paginated APIs in JavaScript
115 Symbol.asyncIterator, paging a source one request at a time
hardWrap a cursor-paged data source in an object with Symbol.asyncIterator, so a caller can write for await (const row of vendors) and never think about cursors. Count the requests, prove the pages were fetched in sequence, show that breaking out early stops fetching, and see what a plain spread does to it.
Stuck? Three hints, smallest first
- 1. An
async *generator method named[Symbol.asyncIterator]is the whole adapter: loop while there is a cursor,awaita page,yieldits rows one at a time. - 2. Yielding rows rather than pages is what hides the paging. The consumer sees a flat sequence and the next request happens when it asks for the row after the last one on a page.
- 3. A
breakin afor awaitcloses the iterator, so the loop that would have asked for the next page never runs. Count the calls to prove it.
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(); // drain, then advance
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 table = [
{ id: 1, name: 'Ngozi Traders' },
{ id: 2, name: 'Bisi Foods' },
{ id: 3, name: 'Chidi Motors' },
{ id: 4, name: 'Amaka Fabrics' },
{ id: 5, name: 'Tunde Spares' },
];
const makeSource = (clock, pageSize) => {
let calls = 0;
return {
get calls() { return calls; },
async fetchPage(cursor) {
calls++;
await clock.wait(10); // one round trip
return {
rows: table.slice(cursor, cursor + pageSize),
next: cursor + pageSize < table.length ? cursor + pageSize : null,
};
},
};
};
const paged = (source) => ({
async *[Symbol.asyncIterator]() {
let cursor = 0;
while (cursor !== null) {
const page = await source.fetchPage(cursor);
for (const row of page.rows) yield row; // hand out rows, not pages
cursor = page.next;
}
},
});
const clockA = makeClock();
const sourceA = makeSource(clockA, 2);
const walkAll = async () => {
const out = [];
for await (const row of paged(sourceA)) out.push(row.name);
return out;
};
const pendingA = walkAll();
await clockA.runAll();
const everyName = await pendingA;
const fullWalk = [sourceA.calls, clockA.now()];
const clockB = makeClock();
const sourceB = makeSource(clockB, 2);
const walkThree = async () => {
const out = [];
for await (const row of paged(sourceB)) {
out.push(row.id);
if (out.length === 3) break; // stop asking
}
return out;
};
const pendingB = walkThree();
await clockB.runAll();
const threeIds = await pendingB;
const shortWalk = [sourceB.calls, clockB.now()];
const clockC = makeClock();
const sourceC = makeSource(clockC, 5);
const iterator = paged(sourceC)[Symbol.asyncIterator]();
const firstStep = iterator.next();
const stepIsAPromise = typeof firstStep.then === 'function';
await clockC.runAll();
const first = await firstStep;
const second = await iterator.next();
const rest = [];
let step = await iterator.next();
while (!step.done) {
rest.push(step.value.id);
step = await iterator.next();
}
let spreadError = 'no error';
try { [...paged(sourceA)]; } catch (e) { spreadError = e.constructor.name; }
const clockE = makeClock();
const sourceE = makeSource(clockE, 5);
const feed = paged(sourceE);
const walkFeed = async () => {
const out = [];
for await (const row of feed) out.push(row.id);
return out;
};
const firstPass = walkFeed();
await clockE.runAll();
const pass1 = await firstPass;
const secondPass = walkFeed();
await clockE.runAll();
const pass2 = await secondPass;
console.log('all rows :', everyName);
console.log('requests :', fullWalk, '| after break:', shortWalk);
console.log('manual :', first.value.name, second.value.name, rest, '| done:', step.done);
console.log('twice :', pass1, pass2, '| requests:', sourceE.calls);
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.
test('every row across every page arrives, in order, with no cursor in sight', everyName, ['Ngozi Traders', 'Bisi Foods', 'Chidi Motors', 'Amaka Fabrics', 'Tunde Spares']);
test('five rows at two a page took three requests, one after another', fullWalk, [3, 30]);
test('breaking out after three rows stops at the second page', [threeIds, shortWalk], [[1, 2, 3], [2, 20]]);
test('next() hands back a promise of { value, done }', [stepIsAPromise, first.done, first.value.name], [true, false, 'Ngozi Traders']);
test('each call advances one row, buffered from the page already fetched', [second.value.name, rest], ['Bisi Foods', [3, 4, 5]]);
test('when the rows run out, done is true and value is undefined', [step.done, step.value === undefined], [true, true]);
test('a plain spread throws, because that wants Symbol.iterator and this has the async one', spreadError, 'TypeError');
test('the iterable can be walked twice: a fresh iterator each time, so it fetches again', [pass1, pass2, sourceE.calls, clockE.now()], [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], 2, 20]);
An async iterable is the right shape for anything that arrives in instalments: paged HTTP responses, database cursors, a websocket, lines from a file. The consumer writes one for await loop and the cursor bookkeeping disappears into the adapter. Yielding rows rather than pages is what makes that work — the caller never sees a page boundary, and the next request happens exactly when it asks for the row after the last one it was given.
Laziness is the property being asserted, and the request count is how you see it. The break case does two requests instead of three, so a consumer that only wants the first few rows does not pay for the rest of the table. That is why this beats fetching everything into an array first, and it is the same argument as the synchronous lazy pipeline, one await deeper.
Three details to keep in mind. Symbol.asyncIterator and Symbol.iterator are separate protocols: for await looks for the async one, while spread, destructuring and for...of look for the sync one and throw here. A fresh iterator per call means the object can be walked twice, at the cost of fetching everything again — whereas the iterator you get from [Symbol.asyncIterator]() is single-use, as the manual walk shows. And for await is strictly sequential: it awaits each value before asking for the next, so if you want several pages in flight at once, this is the wrong tool and something like mapLimit over a list of cursors is the right one.