Async Programming (asyncio & await)
asyncio enables concurrent execution for I/O-bound operations. Write async functions with async def and await, running thousands of tasks concurrently.
20 min•By Priygop Team•Updated 2026
Async Programming
Async Programming
import asyncio
# Async function (coroutine)
async def fetch_data(url, delay):
print(f" Fetching {url}...")
await asyncio.sleep(delay * 0.01) # non-blocking!
print(f" Done: {url}")
return f"Data from {url}"
# Run single coroutine
async def main():
result = await fetch_data("api/users", 1)
print(f" Result: {result}")
asyncio.run(main())
# Run multiple coroutines concurrently
async def main_concurrent():
tasks = [
fetch_data("api/users", 2),
fetch_data("api/posts", 3),
fetch_data("api/comments", 1),
]
results = await asyncio.gather(*tasks)
print(f" All results: {results}")
print("\n--- Concurrent ---")
asyncio.run(main_concurrent())
# Async context manager
class AsyncDB:
async def __aenter__(self):
print(" Connecting to DB...")
await asyncio.sleep(0.01)
return self
async def __aexit__(self, *args):
print(" Disconnected.")
async def query(self, sql):
await asyncio.sleep(0.01)
return [{"id": 1, "name": "Alice"}]
async def use_db():
async with AsyncDB() as db:
result = await db.query("SELECT * FROM users")
print(f" Query result: {result}")
print("\n--- Async DB ---")
asyncio.run(use_db())Tip
Tip
Use async with for async context managers and async for for async iteration. Libraries like aiohttp and asyncpg support these.
Diagram
Loading diagram…
asyncio = concurrent I/O. For CPU tasks use multiprocessing.
Common Mistake
Warning
Forgetting to await async functions. Calling async_func() without await returns a coroutine object instead of the result.
Quick Quiz
Practice Task
Note
(1) Create an async database connection pattern. (2) Use async generators for streaming data. (3) Implement an async retry mechanism.