我试图在异步函数运行完成后调用回调
这是我想做的一个例子:
import asyncio
async def asyncfunction():
print('Hello')
await asyncio.sleep(10)
print('World')
return 10
def callback(n):
print(f'The async function returned: {n}')
loop = asyncio.get_event_loop()
# Will block the print until everything is done
callback(loop.run_until_complete(asyncfunction()))
print('Hey')
这是它的作用:
Hello
World
The async function returned: 10
Hey
这就是我想要它做的
编辑:“嘿”的位置并不重要,只要它不必等待异步函数完成即可
Hello
Hey
World
The async function returned: 10
编辑:经过一些测试,我找到了一种可以实现我想要的功能的方法,尽管我不知道这是否是最好的方法
import asyncio
import threading
async def asyncfunction():
print('Hello')
await asyncio.sleep(10)
print('World')
return 10
def callback(n):
print(f'The async function returned: {n}')
def wrapper(loop):
callback(loop.run_until_complete(asyncfunction()))
loop = asyncio.get_event_loop()
thr = threading.Thread(target=wrapper,args=(loop,))
thr.start()
print('Hey')
将线程与 asyncio 结合使用只是令人困惑,而且很可能不是您想要的。run_until_complete
是阻塞调用之一,并且可能是语句中的最后一个语句asyncio
程序。
要在调用异步函数后添加代码,只需创建一个包装器
async def myfunc():
n = await asyncfunction()
callback(n)
loop.run_until_complete(myfunc()) # from python 3.7, asyncio.run(myfunc())
如果您只想安排一些代码异步运行并继续执行其他操作,请创建一个任务并在最后等待
async def a_main():
task = asyncio.ensure_future(myfunc()) # from python 3.7, asyncio.create_task(...)
print("Hey")
# Anything else to run
await task # wait for the task to complete
loop.run_until_complete(a_main())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)