CKTIS / Python
asyncio.wait
Recebe uma coleção não vazia de tarefas ou Future.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
await asyncio.wait(aws, *, timeout=None, return_when=asyncio.ALL_COMPLETED)Recebe uma coleção não vazia de tarefas ou Future.
Os objetos corrotina isolados são rejeitados. return_when escolhe a primeira conclusão, a primeira exceção ou todas as conclusões. Ao expirar devolve os conjuntos done e pending sem TimeoutError nem cancelamento.
No exemplo uma tarefa terminou e a outra espera o sinal.
import asyncio
async def main():
loop = asyncio.get_running_loop()
a, b = loop.create_future(), loop.create_future()
a.set_result(2)
done, pending = await asyncio.wait([a, b], return_when=asyncio.FIRST_COMPLETED)
assert done == {a} and pending == {b} and not b.cancelled()
b.cancel()
try:
await asyncio.wait([])
except ValueError:
pass
else:
raise AssertionError
asyncio.run(main())
Exemplos
import asyncio
async def main():
gate = asyncio.Event()
pending_task = asyncio.create_task(gate.wait())
finished = asyncio.create_task(asyncio.sleep(0, result=5))
await finished
done, pending = await asyncio.wait([finished, pending_task], timeout=0)
print(len(done), len(pending), pending_task.cancelled())
gate.set()
await pending_task
asyncio.run(main())
Resultado
1 1 False
No exemplo uma tarefa terminou e a outra espera o sinal.