advancedAdvanced Topics

Async Programming

Write concurrent code with async/await for I/O-bound tasks.

In this lesson

01Async Basics

Use async def and await for non-blocking I/O operations.

Python
1import asyncio
2
3async def fetch_data(url: str, delay: float):
4 print(f"Fetching {url}...")
5 await asyncio.sleep(delay) # simulates I/O
6 return f"Data from {url}"
7
8async def main():
9 # Run concurrently
10 results = await asyncio.gather(
11 fetch_data("api/users", 1.0),
12 fetch_data("api/posts", 0.5),
13 fetch_data("api/comments", 0.8),
14 )
15 for r in results:
16 print(r)
17
18asyncio.run(main())
Output
Fetching api/users...
Fetching api/posts...
Fetching api/comments...
Data from api/users
Data from api/posts
Data from api/comments