import asyncio
results = await asyncio.gather(*(fetch_json(u) for u in urls))
first = await asyncio.wait_for(call(), timeout=5)
# entry point of a script:
asyncio.run(main())
Calling an async def function returns a coroutine object; nothing runs until it's awaited or scheduled. A missing await is the #1 asyncio bug.
Concurrency, not parallelism: asyncio runs on one thread and switches at await points. It's ideal for I/O (HTTP, DB, LLM calls). CPU-heavy work blocks the loop — move it to a thread/process pool with asyncio.to_thread().
Bounding concurrency — don't fire 10,000 requests at once
sem = asyncio.Semaphore(5)
async def limited(coro_fn, *args):
async with sem:
return await coro_fn(*args)
Practice
1. Bounded concurrent map
medium25 XP
Write async def bounded_map(fn, items, limit) that runs the async fn(item) for every item with at most limit running at once, and returns results in input order.
Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor