Skip to main content

Async/Await in Practice

Asyncio Core

Async/Await Crash Course

Coroutines let you write sequential-looking code that cooperatively multitasks.

Structure

import asyncio

async def fetch_order(order_id):
await asyncio.sleep(0.1)
return {'id': order_id}

async def main():
order = await fetch_order('123')
print(order)

asyncio.run(main())
  • async declares coroutines; await pauses until awaited tasks complete.
  • Use asyncio.run to bootstrap top-level coroutines.

Gathering tasks

orders = await asyncio.gather(
fetch_order('123'),
fetch_order('456'),
fetch_order('789'),
return_exceptions=True,
)
  • asyncio.gather waits for all tasks; pass return_exceptions=True to avoid cancellation.
  • asyncio.create_task schedules background work; keep references so you can await or cancel later.

Error handling

  • Wrap awaits in try/except just like synchronous code.
  • Use asyncio.TimeoutError with asyncio.wait_for to enforce deadlines.
  • Cancel tasks with task.cancel() to clean up when shutting down.

Next up in your learning path