CodShot
TypeScript Public

Async Generator for Paginated API Data

Iterate through paginated API responses without loading every page into memory.

#typescript #async #pagination #api
TypeScript
type Page<T> = {
  items: T[];
  nextCursor: string | null;
};

export async function* paginate<T>(
  buildUrl: (cursor: string | null) => string,
): AsyncGenerator<T, void, void> {
  let cursor: string | null = null;

  do {
    const response = await fetch(buildUrl(cursor));

    if (!response.ok) {
      throw new Error(
        `Pagination request failed: ${response.status}`,
      );
    }

    const page = await response.json() as Page<T>;

    for (const item of page.items) {
      yield item;
    }

    cursor = page.nextCursor;
  } while (cursor);
}

// Usage:
// for await (const user of paginate<User>(buildUsersUrl)) {
//   console.log(user);
// }

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support