Py/asyncio/How To/Use gather and await to wait for multiple futures
Properties
- tags
- Diataxis/How To
How to use Py/asyncio/gather and Py/asyncio/wait to await multiple futures
Overview
Prerequisites
Steps
1. Using asyncio.gather
- Best for when you want to run multiple coroutines concurrently and collect all their results
- Example:
- python
import asyncio async def fetch_data(id: int) -> dict: await asyncio.sleep(1) # Simulating API call return {"id": id, "data": f"result_{id}"} async def main(): # Run three fetch operations concurrently results = await asyncio.gather( fetch_data(1), fetch_data(2), fetch_data(3) ) print(results) # [{"id": 1, ...}, {"id": 2, ...}, {"id": 3, ...}] asyncio.run(main())
- Key points about
gather:
2. Using asyncio.wait
- Best for more fine-grained control over multiple coroutines
- Example:
- python
import asyncio from asyncio import FIRST_COMPLETED async def process_data(id: int) -> str: await asyncio.sleep(id) # Different delays return f"Task {id} completed" async def main(): # Create task objects tasks = [ asyncio.create_task(process_data(i)) for i in range(1, 4) ] # Wait for first task to complete done, pending = await asyncio.wait( tasks, return_when=FIRST_COMPLETED ) # Process completed task for task in done: print(f"First result: {task.result()}") # Cancel remaining tasks for task in pending: task.cancel() asyncio.run(main())
- Key points about
wait:
3. Choosing between gather and wait
Troubleshooting
Related