Async Programming
Prerequisites: Concurrency and parallelism
async/await lets a program work on other tasks while waiting on
something slow (a network request, a database query), instead of
sitting idle.
import asyncio
async def fetch_data(id):
await asyncio.sleep(1) # simulates a slow network call
return f"data-{id}"
async def main():
results = await asyncio.gather(
fetch_data(1), fetch_data(2), fetch_data(3),
)
print(results)
asyncio.run(main())
Expected output
['data-1', 'data-2', 'data-3']
asyncio.gather runs all three fetch_data calls concurrently — the
whole program waits about 1 second total, not 3, since they overlap
while each is "waiting."
Common mistakes
- Calling an
async deffunction withoutawait— it returns a not-yet-run coroutine object instead of the actual result.