Async Generator Batched Iteration
Pull remote pages lazily through an async generator, batching records per yield so consumers control pacing and memory stays flat.
Code
async function* paginate(source, pageSize = 100) {
let offset = 0;
while (true) {
const rows = await source(offset, pageSize);
if (rows.length === 0) return;
yield rows;
offset += rows.length;
}
}
async function* flatten(batches) {
for await (const batch of batches) {
for (const row of batch) {
yield row;
}
}
}
const remote = async (offset, limit) => {
const res = await fetch(
'https://api.example.com/records?offset=' + offset + '&limit=' + limit,
);
const body = await res.json();
return body.rows;
};
let total = 0;
for await (const row of flatten(paginate(remote))) {
total += row.amount;
if (total > 10_000) break; // 消费者随时可提前退出
}
console.log('accumulated amount:', total);How the snippet works
Async Generator Batched Iteration keeps everything in the function remote.
Two loops stack here: while (true) selects, for await (const batch of batches) processes. The async parts await their results, which keeps ordering predictable.
What to watch for
- Uses
fetch, so it needs a browser context — it will not run as-is in Node without shims. - The guard
rows.length === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads const remote = async (offset, limit)
The demo output is labeled (accumulated amount:), so every printed line maps back to its originating operation.
Key statements
for await (const row of flatten(paginate(remote))) {
total += row.amount;
if (total > 10_000) break; // 消费者随时可提前退出
}
const rows = await source(offset, pageSize);
const remote = async (offset, limit) => {
const res = await fetch(
'https://api.example.com/records?offset=' + offset + '&limit=' + limit,
);
const body = await res.json();
return body.rows;
};
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `remote` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.