Async Generator Paginating APIs

Wrap cursor pagination in an async generator so callers consume pages with for await and stop early without managing tokens.

TypescriptData Fetching

Code

typescriptsnippet
39 lines
interface Page<T> {
  items: T[];
  nextCursor: string | null;
}

interface Row {
  id: number;
  name: string;
}

async function fetchPage(cursor: string | null): Promise<Page<Row>> {
  // 演示用:真实实现换成 fetch 调用
  const start = cursor === null ? 1 : Number(cursor);
  const items = Array.from({ length: 3 }, (_, i) => ({ id: start + i, name: 'row-' + (start + i) }));
  const nextCursor = start + 3 > 7 ? null : String(start + 3);
  return { items, nextCursor };
}

async function* allRows(): AsyncGenerator<Row> {
  let cursor: string | null = null;
  do {
    const page = await fetchPage(cursor);
    for (const row of page.items) yield row;
    cursor = page.nextCursor;
  } while (cursor !== null);
}

async function main(): Promise<void> {
  let seen = 0;
  // 消费端可随时 break:生成器不再继续翻页
  for await (const row of allRows()) {
    seen += 1;
    if (seen > 5) break;
    console.log(row.id, row.name);
  }
  console.log('consumed:', seen);
}

void main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1 row-1
2 row-2
3 row-3
4 row-4
5 row-5
consumed: 6

How it works

Async Generator Paginating APIs reduces to the functions fetchPage and main.

Iteration is nested: for (const row of page.items) yield row; frames the pass, for await (const row of allRows()) does the per-item step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying items.

Watch out for

  • The guard seen > 5 short-circuits the flow with an early break when its condition holds.

Applying it

The primary signature is async function fetchPage(cursor: string | null)

The demo output is labeled (consumed:), so every line of output points back to the operation that emitted it.

The call returns items.

Statements that matter

const items = Array.from({ length: 3 }, (_, i) => ({ id: start + i, name: 'row-' + (start + i) }));
for (const row of page.items) yield row;
async function main(): Promise<void> {
let seen = 0;
// 消费端可随时 break:生成器不再继续翻页
for await (const row of allRows()) {
seen += 1;
if (seen > 5) break;
console.log(row.id, row.name);
}
console.log('consumed:', seen);
}

FAQ

Does `fetchPage` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
What does Async Generator Paginating APIs print when run?
Invoke the file as-is — the `consumed:` prefixes identify which step printed each line.