【问题标题】:Pass return value from coroutine to callback function without using await将返回值从协程传递给回调函数而不使用等待
【发布时间】:2021-07-12 16:29:44
【问题描述】:
import asyncio

async def f():
    # something, for example await asyncio.sleep(4)
    return "return value from f"

async def main():
    # schedule f, print result, but don't await
    for i in range(10):
        await asyncio.sleep(1)  # just an example for some other task
        print(i)

asyncio.run(main())

我可以使用print(await f()),但由于await 而阻塞。我希望printf() 返回后被称为“回调函数”,而main() 的其余部分已经继续。因此,假设f 中的# something 花费了 4 秒,预期的输出将如下所示:

0
1
2
3
return value from f
4
5
6
7
8
9

【问题讨论】:

标签: python async-await python-asyncio coroutine


【解决方案1】:

您可以定义一个以f 和回调函数为参数的函数。

async def call(f, cb):
    cb(await f())

你可以在不使用 await 的情况下为其安排任务:

asyncio.create_task(call(f, print))

【讨论】:

    【解决方案2】:

    这对你有用吗?我稍微改变了 f() 协程,但这似乎确实有效。此外,您需要等待 asyncio.sleep()。让我知道您的想法或如果您有任何问题。

    这是我引用的答案:How I call an async function without await?

    import asyncio
    
    async def f():
        await asyncio.sleep(3)
        print("return value from f")
    
    async def main():
        loop = asyncio.get_event_loop()
        loop.create_task(f())
        for i in range(10):
            await asyncio.sleep(1)  # just an example for some other task
            print(i)
    
    asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2019-07-25
      • 1970-01-01
      • 2019-03-12
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2018-01-03
      相关资源
      最近更新 更多