Asyncio Tasks, Futures & asyncio.gather()
1Concept
`asyncio.create_task()` wraps a coroutine into a `Task` and schedules it on the event loop immediately. `asyncio.gather(*tasks)` runs multiple concurrent tasks in parallel, waiting for all to resolve and returning results in submission order.
2Architecture Diagram
asyncio.gather(Task A, Task B, Task C) ---> Concurrently executes all 3 ---> Returns [resA, resB, resC]
3Code Example
Python 3.12
import asyncio
async def simulate_api(endpoint: str, latency: float) -> str:
await asyncio.sleep(latency)
return f"Response from {endpoint}"
async def main():
# Schedule both calls concurrently
res1, res2 = await asyncio.gather(
simulate_api("/users", 0.02),
simulate_api("/orders", 0.01)
)
print(res1)
print(res2)
asyncio.run(main())4Expected Output
Response from /users Response from /orders
5Key Takeaways
- ✓`asyncio.gather()` preserves result ordering matching the input argument order.
- ✓Pass `return_exceptions=True` to prevent a single failure from aborting all gathered tasks.
- ✓Always maintain references to running tasks to prevent garbage collection mid-execution.