简体   繁体   English

在 asyncio.gather 中内联链 asyncio 协程

[英]Chain asyncio coroutines inline in asyncio.gather

I have a hypothetical asyncio.gather scenario:我有一个假设的asyncio.gather场景:

await asyncio.gather(
    cor1,
    [cor2, cor3],
    cor4,
)

I'd like cor2 and cor3 to be executed in order here.我想在这里按顺序执行cor2cor3 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. asyncio 不提供开箱即用的功能。 If asyncio tasks had a method equivalent to JavaScript's Promise.then , you'd be able to use asyncio.create_task(cor2()).then(cor3()) .如果 asyncio 任务有一个等同于 JavaScript 的Promise.then的方法,你就可以使用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.但是 asyncio 等价物add_done_callback是一个更底层的构造, add_done_callback设置回调而不创建新的未来,这使得链接不方便。

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:然后你可以调用gather为:

await asyncio.gather(cor1(), chain(cor2(), cor3()), cor4())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM