15.3. AsyncIO Wait
asyncio.wait(aws, timeout)
wait()
- when a timeout occurs: does not cancel the futuresIf aw is a coroutine it is automatically scheduled as a Task
Returns those implicitly created Task objects in (done, pending) sets
15.3.1. SetUp
>>> import asyncio
15.3.2. Wait
Coroutine
asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
aws
must be iterable (list, tuple, set)aws
iterable must not be emptyRun awaitable objects in the
aws
concurrently and block until the condition specified byreturn_when
timeout: float|int
if specified, maximum number of seconds to wait before returningwait()
does not cancel the futures when a timeout occursIf
gather()
is cancelled (ie. on timeout), all submitted awaitables (that have not completed yet) are also cancelledreturn_when
indicates when this function should returnreturn_when
must be one ofFIRST_COMPLETED
,FIRST_EXCEPTION
,ALL_COMPLETED
return_when=FIRST_COMPLETED
- The function will return when any future finishes or is cancelled;return_when=FIRST_EXCEPTION
- The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED;return_when=ALL_COMPLETED
- The function will return when all futures finish or are cancelledDoes not raise
asyncio.TimeoutError
Futures
orTasks
that aren't done when the timeout occurs are simply returned in the second set (pending
).
done, pending = await asyncio.wait(aws)
>>> async def work():
... return 'done'
>>>
>>>
>>> async def main():
... task = asyncio.create_task(work())
... done, pending = await asyncio.wait({task})
...
... if task in done:
... print('work is done')
>>>
>>>
>>> asyncio.run(main())
work is done