wait
- Python course
- Advanced
- Lesson 32/83
- 5 min
Learn first-to-finish with asyncio.wait.
wait
asyncio.wait awaits a group of coroutines or Tasks; it does not have to wait for all of them. It can be set to wait for the first completion, the first error, or all.
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)It returns two sets: done (completed) and pending (still waiting). The return_when parameter sets when to return: ALL_COMPLETED, FIRST_COMPLETED or FIRST_EXCEPTION.
gather returns results in order; wait works with Task objects and gives finer control.
done and pending sets
The done set returned by wait holds completed Tasks; pending holds the still-waiting ones. Both contain Task objects.
When it returns on first completion, you can cancel the pending Tasks or keep waiting. This is useful for timeouts and cancellation logic.
for t in pending:
t.cancel()This control gives flexibility that gather does not.
Practice First completion with wait
Start with import asyncio. The function async def slow() does await asyncio.sleep(0); return 42. Inside async def main() build tasks = [asyncio.create_task(slow())]; call done, pending = await asyncio.wait(tasks). Return return list(done)[0].result(). Add print(asyncio.run(main())).
Starter code
# import the asyncio module
# declare a coroutine named slow; wait zero seconds, return 42
# main coroutine builds a Task list with create_task, awaits via wait
# return the result of the first done Task; print main via asyncio.runSample solution
import asyncio
async def slow():
await asyncio.sleep(0)
return 42
async def main():
tasks = [asyncio.create_task(slow())]
done, pending = await asyncio.wait(tasks)
return list(done)[0].result()
print(asyncio.run(main()))Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 wait return_when
done, pending = await asyncio.wait(tasks,
return_when=asyncio.____)
done, pending = await asyncio.wait(tasks,
return_when=asyncio.FIRST_COMPLETED)
Explanation: asyncio.FIRST_COMPLETED returns when the first task completes.
2 Match the wait concepts
| Term | Meaning |
|---|---|
asyncio.wait |
Awaits Tasks |
done |
Completed |
pending |
Still waiting |
FIRST_COMPLETED |
Return on first |
3 What does asyncio.wait return?
- Only a list of results
- A single Task
- Two sets: done and pending Correct answer
- Nothing
Explanation: wait returns two sets: done and pending.