await — Intermediate Playground
Pauses execution of an async coroutine until a result is available
Python Playground
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())
Output
Click "Run" to execute your code
Exceptions from awaited coroutines propagate normally and can be caught with try/except. asyncio.wait_for adds timeout support.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?