Async generators combine async def and yield for asynchronous iteration.
1import asyncio23async def fetch_page(url, page):4 await asyncio.sleep(0.5) # Simulate network5 return {"url": url, "page": page, "data": f"Page {page}" }67async def paginate_all(url):8 page = 19 while True:10 data = await fetch_page(url, page)11 yield data # Async yield12 if not data.get("has_next"):13 break14 page += 11516async def main():17 async for page in paginate_all("https://api.example.com"):18 process(page)1920asyncio.run(main())
Use cases:
Key differences from regular generators:
async for to consume.await inside the generator.