async — Intermediate Examples
Declares an asynchronous coroutine function or context manager
Concurrent tasks with async
Running multiple async operations concurrently.
python
import asyncio async def task(name, delay): print(f" {name}: starting") await asyncio.sleep(delay) print(f" {name}: done after {delay}s") return f"{name}-result" async def main(): # Run tasks concurrently with gather results = await asyncio.gather( task("A", 0.02), task("B", 0.01), task("C", 0.03), ) print(f"Results: {results}") asyncio.run(main())
asyncio.gather() runs multiple coroutines concurrently. Unlike threads, async switches tasks at await points, not preemptively.
Async iteration
Using async for and async generators.
python
import asyncio async def countdown(name, n): for i in range(n, 0, -1): yield f"{name}: {i}" await asyncio.sleep(0) async def main(): async for msg in countdown("Timer", 3): print(msg) # Async comprehension values = [msg async for msg in countdown("Gen", 3)] print(values) asyncio.run(main())
Expected Output
Timer: 3 Timer: 2 Timer: 1 ['Gen: 3', 'Gen: 2', 'Gen: 1']
async for iterates over async generators (functions with yield and async). async comprehensions work just like regular comprehensions but inside async contexts.
Want to try these examples interactively?
Open Intermediate Playground