JavaScriptFundamental (ES6), part 1
Paginate with an async generator in JavaScript
139 paging through results with an async generator
hardWrap a cursor-paged listing in an async function* that yields one page at a time, then a second one that flattens it to individual rows. Consume it with for await...of, count how many page requests each consumer causes, and show that stopping after four rows fetched two pages rather than all three. Then check what for await does with a yielded promise.
Stuck? Three hints, smallest first
- 1. The page generator is a
whileloop over the cursor:awaitthe page,yieldits rows, take the next cursor, stop when it is null. - 2. To flatten, iterate the first generator with
for awaitandyieldeach row inside it. - 3. Nothing is fetched until someone pulls, which is why breaking out of the loop early stops the requests — and runs the generator’s
finally.
const ALL = ['Ada', 'Bola', 'Chidi', 'Dele', 'Efe', 'Funke', 'Gbenga'];
const PAGE_SIZE = 3;
let requests = 0;
const fetchPage = async (cursor) => {
requests += 1;
const rows = ALL.slice(cursor, cursor + PAGE_SIZE);
const nextCursor = cursor + PAGE_SIZE < ALL.length ? cursor + PAGE_SIZE : null;
return { rows, nextCursor };
};
async function* pages() {
let cursor = 0;
while (cursor !== null) {
const page = await fetchPage(cursor);
yield page.rows;
cursor = page.nextCursor;
}
}
async function* rows() {
for await (const page of pages()) {
for (const row of page) yield row;
}
}
const takeAsync = async (source, count) => {
const out = [];
if (count <= 0) return out;
for await (const value of source) {
out.push(value);
if (out.length >= count) break;
}
return out;
};
const everyone = [];
for await (const name of rows()) everyone.push(name);
const requestsForEveryone = requests;
requests = 0;
const firstFour = await takeAsync(rows(), 4);
const requestsForFour = requests;
requests = 0;
const none = await takeAsync(rows(), 0);
const requestsForNone = requests;
async function* mixed() {
yield 'plain';
yield Promise.resolve('a promise, unwrapped');
}
const unwrapped = [];
for await (const value of mixed()) unwrapped.push(value);
const overAnArray = [];
for await (const value of [Promise.resolve('a'), 'b']) overAnArray.push(value);
let cleaned = false;
async function* watched() {
try {
yield 'one';
yield 'two';
} finally {
cleaned = true;
}
}
const justOne = await takeAsync(watched(), 1);
const lastPage = await fetchPage(6);
console.log('everyone :', everyone, '| requests:', requestsForEveryone);
console.log('firstFour:', firstFour, '| requests:', requestsForFour);
console.log('cleanup :', cleaned, '| none:', none, requestsForNone);
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 arrives, in order, across the pages', everyone, ALL);
test('seven rows at three a page took three requests', requestsForEveryone, 3);
test('stopping after four rows only needed two of them', [firstFour, requestsForFour], [['Ada', 'Bola', 'Chidi', 'Dele'], 2]);
test('asking for none never touches the source at all', [none, requestsForNone], [[], 0]);
test('for await unwraps a yielded promise for you', unwrapped, ['plain', 'a promise, unwrapped']);
test('and it does the same over a plain array holding one', overAnArray, ['a', 'b']);
test('breaking out early still runs the generator\'s finally', [justOne, cleaned], [['one'], true]);
test('the last page reports a null cursor, which is what ends the loop', lastPage, { rows: ['Gbenga'], nextCursor: null });
Cursor paging is the shape almost every list API has, and it leaks into calling code as a while loop with a mutable cursor, repeated at every call site. An async function* puts that loop in one place and hands out a sequence, so the consumer writes for await (const row of rows()) and never sees a cursor. The two-generator split is worth copying: one yields pages, one flattens to rows, and a caller takes whichever granularity it needs.
The request counts are the reason to bother. Because a generator only runs when pulled, the consumer's stopping condition controls the network: four rows, two pages, third never requested. A function that returned an array would have fetched everything before the caller could say it had enough. And a break is not just a local exit — it closes the async iterator, which resumes the generator with a return completion and runs its finally, so a connection or a transaction gets released.
Two smaller facts. for await awaits each value, so a yielded promise arrives resolved, and it works over an ordinary array of promises too — handy, though for independent work Promise.all is the right tool because for await is strictly sequential. Note this whole exercise is deterministic: fetchPage is async but never touches a timer or the network, which is what makes the request counts assertable.