Use `asyncio.wait()` to control waiting behavior.
Section: Tasks and Concurrency
Wait until the first task completes
python
python
import asyncio
async def worker(name, delay):
await asyncio.sleep(delay)
return name
async def main():
tasks = {asyncio.create_task(worker("fast", 0.1)), asyncio.create_task(worker("slow", 1))}
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
print(task.result())
for task in pending:
task.cancel()
asyncio.run(main())Explanation
Useful for races and cancellation patterns.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Tasks and Concurrency
Run tasks concurrently with gather
Wait for multiple coroutines and collect results.
Collect exceptions with gather
Keep other tasks running even if one fails.
Use TaskGroup for structured concurrency
Run related tasks under a context manager.
Consume results as tasks finish
Process faster tasks first using `as_completed()`.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.