非常简单的代码:
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?我想通过将它作为可调用/lambda传递给“调用者”函数来调用“轮询”。通常,在一种设计良好的语言(例如C# )中,您会执行poll().Result,因为轮询()返回一个任务,该任务包含诸如Wait()和returns来阻止和等待的方法,如果您想阻止并等待并返回到当前异步方法的调用者,则可以使用“等待”。
发布于 2022-01-08 17:17:56
当声明一个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())-编辑--
要运行协同线,您在asyncio中有3个选项。
time.
await function
asyncio.create_task()中运行:在代码的某个地方也需要等待
当您不等待选项2和3时,协同器就不会执行。因此,您在这里要做的事情不能通过asyncio包来实现。
我真正不明白的是,为什么要执行一个async函数来等待它同步运行?这违背了使用任务的目的。
https://stackoverflow.com/questions/70634627
复制相似问题