add_done_callback被认为是“低级”界面。使用协程时,可以通过多种方式链接它们,例如:
import asyncioasync def my_callback(result): print("my_callback got:", result) return "My return value is ignored"async def coro(number): await asyncio.sleep(number) return number + 1async def add_success_callback(fut, callback): result = await fut await callback(result) return resultloop = asyncio.get_event_loop()task = asyncio.ensure_future(coro(1))task = add_success_callback(task, my_callback)response = loop.run_until_complete(task)print("response:", response)loop.close()
请记住,
add_done_callback如果您的将来引发异常,仍会调用回调(但调用
result.result()会引发异常)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)