我想在Python代码中重现javascript的Promise.race行为。我希望同时运行一组协程,并在第一个协程完成时返回,获取其结果,并取消/丢弃仍在运行的协程的结果。
发布于 2018-12-29 15:07:10
可以在参数return_when设置为FIRST_COMPLETED的情况下使用asyncio.wait。下面的示例代码将打印1,并且永远不会引发异常。第二个for循环确保所有挂起的协程都正确完成。如果raising_wait协程首先完成,则在调用创建的任务对象的result方法后,将按照文档中指定的方式引发异常。最后值得一提的是,在FIRST_COMPLETED中使用asyncio.wait并不能保证,如果两个例程在几乎相同的时间内完成,我们将在完成集合中恰好有一个任务。
from contextlib import suppress
import asyncio
async def wait(t):
await asyncio.sleep(t)
return t
async def raising_wait(t):
await asyncio.sleep(t)
raise TimeoutError("You waited for too long, pal")
loop = asyncio.new_event_loop()
task_set = set()
task_set.add(loop.create_task(wait(1)))
task_set.add(loop.create_task(raising_wait(2)))
task_set.add(loop.create_task(wait(3)))
done_first, pending = loop.run_until_complete(
asyncio.wait(task_set, return_when=asyncio.FIRST_COMPLETED)
)
for coro in done_first:
try:
print(coro.result())
except TimeoutError:
print("cleanup after error before exit")
for p in pending:
p.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(p)
loop.close()https://stackoverflow.com/questions/53967281
复制相似问题