await — Intermediate Examples
Pauses execution of an async coroutine until a result is available
Await with error handling
Handling exceptions from awaited coroutines.
python
import asyncio async def risky_operation(should_fail): await asyncio.sleep(0) if should_fail: raise ValueError("Something went wrong") return "success" async def main(): # try/except works with await try: result = await risky_operation(True) except ValueError as e: print(f"Caught: {e}") result = await risky_operation(False) print(f"Result: {result}") # Timeout with wait_for async def slow(): await asyncio.sleep(10) return "done" try: result = await asyncio.wait_for(slow(), timeout=0.01) except asyncio.TimeoutError: print("Operation timed out!") asyncio.run(main())
Expected Output
Caught: Something went wrong Result: success Operation timed out!
Exceptions from awaited coroutines propagate normally and can be caught with try/except. asyncio.wait_for adds timeout support.
Awaiting multiple things
Patterns for awaiting concurrent operations.
python
import asyncio async def fetch(name, delay): await asyncio.sleep(delay) return f"{name}_data" async def main(): # Sequential (slow) a = await fetch("A", 0.01) b = await fetch("B", 0.01) print(f"Sequential: {a}, {b}") # Concurrent (fast) a, b = await asyncio.gather( fetch("A", 0.01), fetch("B", 0.01), ) print(f"Concurrent: {a}, {b}") # as_completed: process in completion order tasks = [fetch("slow", 0.03), fetch("fast", 0.01), fetch("mid", 0.02)] for coro in asyncio.as_completed(tasks): result = await coro print(f" Completed: {result}") asyncio.run(main())
Sequential awaits run one after another. asyncio.gather runs them concurrently. as_completed yields results in the order they finish.
Want to try these examples interactively?
Open Intermediate Playground