javascript / expert
Snippet
Asynchronous Generator Control Flow for Paginated Route Streaming
This expert snippet uses asynchronous generators (`async function*`) to manage sequential control flow over paginated external API responses within Next.js Route Handlers. It lazily yields unarchived log items one by one, allowing memory-efficient streaming without loading all pages into memory at once.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
export async function* fetchPaginatedAuditLogs(initialUrl) {let nextUrl = initialUrl;while (nextUrl) {const res = await fetch(nextUrl, { headers: { 'Accept': 'application/json' } });if (!res.ok) throw new Error(`HTTP fetch failure: ${res.status}`);const data = await res.json();nextUrl = data.meta?.nextCursor ? `${initialUrl}?cursor=${data.meta.nextCursor}` : null;for (const record of data.records) {if (record.isArchived) continue;yield record;}}}
nextjs
Breakdown
1
export async function* fetchPaginatedAuditLogs(initialUrl) {
Declares an async generator function returning an AsyncIterator that yields values on demand.
2
while (nextUrl) {
Controls the main execution loop, continuing as long as a valid cursor endpoint remains.
3
if (!res.ok) throw new Error(`HTTP fetch failure: ${res.status}`);
Implements immediate control flow interruption when an unexpected HTTP error status occurs.
4
for (const record of data.records) {
Iterates over the current payload's items.
5
if (record.isArchived) continue;
Uses conditional control flow to skip archived entries before yielding.
6
yield record;
Pauses function execution and emits the current record to the async consumer.