如何在非异步函数中阻塞并等待异步函数的结果?

Spa*_*key 5 python python-asyncio

非常简单的代码:

async def poll():
    await asyncio.sleep(1)

def caller(somefunction):
    somefunction() # we don't know if callable is async or not

def main():
    caller(poll) # how to pass an async function "poll" here?

Run Code Online (Sandbox Code Playgroud)

我想通过将其作为可调用/lambda 传递给“调用者”函数来调用“poll”。通常,在设计良好的语言中,例如 C#,您会这样做poll().Result,因为 poll() 返回一个任务,该任务具有 Wait() 和 Result 等方法来阻止和等待,或者如果您想阻止和等待并返回,您可以使用“await”到您当前所在异步方法的调用者。

Dru*_*ann 0

当声明一个async函数然后调用它时,也需要等待它。与 一样await asyncio.sleep(1),您需要等待callee()。见下文:

import asyncio

async def callee():
    await asyncio.sleep(1)
    print ("first")
    return 1


async def caller():
    await callee() # how do I wait the result of this?
    print("second")


async def main():
    await caller()    


if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())

Run Code Online (Sandbox Code Playgroud)

- 编辑 -

要运行协程,您有 3 个选项asyncio

  1. asyncio.run() 函数:这里不能使用它,因为只能同时运行 1 个事件循环。
  2. await协程:你不希望/不能在同步函数中使用它
  3. With asyncio.create_task(): 也需要在代码中的某个地方等待

当您不等待选项 2 和 3 时,协程就不会执行。因此,您在这里尝试做的事情无法通过该asyncio包来实现。

我真正不明白的是为什么你想执行一个async函数来等待它同步?这违背了使用任务的目的。

  • 您使“呼叫者”异步。我的问题是关于如何在非异步函数中等待 (2认同)