JavaScriptFundamental (ES6), part 2
Hide API pagination behind an async generator in JavaScript
14 Page through a fake API with an async generator
hardHide pagination behind an async generator: the caller iterates items, never pages. Count the requests. Then take only the first three items and show that the third page was never fetched.
Stuck? Three hints, smallest first
- 1. Loop while there is a next page cursor,
awaitthe page, thenyield*its items. - 2.
yield*over a plain array works inside an async generator too. - 3. A
takeAsyncthat returns early stops pulling, and the pull is what triggers the next request.
const PAGES = {
1: { items: ['LAG-001', 'LAG-002'], next: 2 },
2: { items: ['LAG-003', 'LAG-004'], next: 3 },
3: { items: ['LAG-005'], next: null },
};
let requests = 0;
const api = { get(page) { requests++; return Promise.resolve(PAGES[page]); } };
async function* paged(api, from = 1) {
let page = from;
while (page !== null) {
const body = await api.get(page);
yield* body.items; // the caller never sees a page boundary
page = body.next;
}
}
async function* takeAsync(source, n) {
if (n <= 0) return;
let i = 0;
for await (const v of source) { yield v; if (++i === n) return; }
}
const collect = async (source) => {
const out = [];
for await (const v of source) out.push(v);
return out;
};
const everything = await collect(paged(api));
const requestsForAll = requests;
requests = 0;
const firstThree = await collect(takeAsync(paged(api), 3));
const requestsForThree = requests;
const onePage = await collect(paged({ get: () => Promise.resolve({ items: [], next: null }) }));
console.log('all plates :', everything, 'in', requestsForAll, 'requests');
console.log('first three:', firstThree, 'in', requestsForThree, 'requests');
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('paging walks every page', everything, ['LAG-001', 'LAG-002', 'LAG-003', 'LAG-004', 'LAG-005']);
test('which took three requests', requestsForAll, 3);
test('taking three stops early', firstThree, ['LAG-001', 'LAG-002', 'LAG-003']);
test('so only two pages were fetched', requestsForThree, 2);
test('the consumer never sees a page boundary', firstThree.join(','), 'LAG-001,LAG-002,LAG-003');
test('a single empty page terminates cleanly', onePage, []);
test('yield* delegates to a sync iterable inside an async generator', typeof paged(api)[Symbol.asyncIterator], 'function');
This is the shape worth stealing. The pagination cursor, the request loop and the page envelope all stay inside the generator; the caller writes for await (const plate of paged(api)) and is done. Compare the alternative, where every caller maintains a while (nextPage) loop and gets it subtly wrong once.
requestsForThree === 2 is what backpressure looks like without a framework. The second page was fetched because the third item was asked for; the third page was not, because nothing asked. That property is why an async generator beats a callback that receives every page: the consumer's break is a signal the producer can act on.
Two things this version leaves out on purpose. There is no retry, so a failed page rejects the whole loop — compose it with exercise 22's retry around api.get. And there is no cancellation beyond break, which is exercise 15.