原文引用 大专栏 https://www.dazhuanlan.com/2019/08/26/5d635566c43cf/
本文为 Producing Results Asynchronously 的学习笔记
一个 Future
对象表示一项“未完成”的工作。事件循环可以监视 Future
对象的完成情况。
Future
对象的行为和 coroutine
类似,因此等待 coroutine
的方法同样适用于等待 Future
.
123456789101112131415161718192021222324 | import asynciodef (future, result): print('setting future result to {!r}'.format(result)) future.set_result(result) event_loop = asyncio.get_event_loop()try: all_done = asyncio.Future() print('scheduling mark_done') event_loop.call_soon(mark_done, all_done, 'the result') print('entering event loop') result = event_loop.run_until_complete(all_done) print('returned result: {!r}'.format(result))finally: print('closing event loop') event_loop.close() # Future 的 set_result 方法会同时把结果保存在其 result 方法中print('future result: {!r}'.format(all_done.result())) |
Future
对象在调用 set_result()
方法后其状态转变为完成,其行为相当于 coroutine
的 return
, 也会将结果返回给调用该 Future
的位置,同时会把这个结果保存在 Future
对象的 result()
方法中。
执行结果:
123456 | scheduling mark_doneentering event loopsetting future result to 'the result'returned result: 'the result'closing event loopfuture result: 'the result' |
也可以使用 await
关键字来调用 Future
对象
1234567891011121314151617181920212223 | import asynciodef mark_done(future, result): print('setting future result to {!r}'.format(result)) future.set_result(result)async def main(loop): all_done = asyncio.Future() print('scheduling mark_done') loop.call_soon(mark_done, all_done, 'the result') result = await all_done print('returned result: {!r}'.format(result))event_loop = asyncio.get_event_loop()try: event_loop.run_until_complete(main(event_loop))finally: event_loop.close() |
await
会返回 Future
的结果:
123 | scheduling mark_donesetting future result to 'the result'returned result: 'the result' |
Future
对象在完成的时候可以触发回调函数,回调函数触发的顺序与被注册的顺序相同。
123456789101112131415161718192021222324252627282930 | import asyncioimport functoolsdef callback(future, n): # 回调函数的第一个参数是一个 Future print('{}: future done: {}'.format(n, future.result()))async def register_callbacks(all_done): print('registering callbacks on future') # 使用 add_done_callback 注册回调函数 all_done.add_done_callback(functools.partial(callback, n=1)) all_done.add_done_callback(functools.partial(callback, n=2)) # coroutine 对象 register_callbacks 在这里完成async def main(all_done): await register_callbacks(all_done) print('setting result of future') all_done.set_result('the result') # future 对象 all_done 在这里完成,触发回调 # new_event_loop 问题同上节event_loop = asyncio.get_event_loop()try: all_done = asyncio.Future() event_loop.run_until_complete(main(all_done))finally: event_loop.close() |
add_done_callback()
方法只能向回调函数传入一个参数,即调用该方法的 Future
对象本身。如果要向回调函数传入其他参数,需要使用 functool.partial()
方法绑定。
执行结果:
1234 | registering callbacks on futuresetting result of future1: future done: the result2: future done: the result |
参考资料:
来源:博客园
作者:.net零基础入门教程
链接:https://www.cnblogs.com/JimmyShen/p/11411849.html