I have a hypothetical asyncio.gather
scenario:
await asyncio.gather(
cor1,
[cor2, cor3],
cor4,
)
I'd like cor2
and cor3
to be executed in order here. Is there some shortcut way of doing other than defining an outside coroutine like this:
async def cor2_cor3():
await cor2
await cor3
await asyncio.gather(
cor1,
cor2_cor3,
cor4,
)
Is there a cleaner shortcut for this?
Is there a cleaner shortcut for this?
asyncio doesn't provide one out of the box. If asyncio tasks had a method equivalent to JavaScript's Promise.then
, you'd be able to use asyncio.create_task(cor2()).then(cor3())
. But the asyncio equivalent, add_done_callback
, is a more low-level construct which just sets up the callback without creating a new future, which makes it inconvenient for chaining.
To execute coroutines in order you will need to write a simple utility function, for example (untested):
async def chain(*aws):
ret = None
for aw in aws:
ret = await aw
return ret
Then you can invoke gather
as:
await asyncio.gather(cor1(), chain(cor2(), cor3()), cor4())