10.5.4.2 Future回调
除了做法与协程类似,Future完成时也可以调用回调。回调会按其注册的顺序调用。
import asyncio
import functools
def callback(future,n):
print('{}:future done: {}'.format(n,future.result()))
async def register_callbacks(all_done):
print('registering callbacks on future')
all_done.add_done_callback(functools.partial(callback,n=1))
all_done.add_done_callback(functools.partial(callback,n=2))
async def main(all_done):
await register_callbacks(all_done)
print('setting result of future')
all_done.set_result('the result')
event_loop = asyncio.get_event_loop()
try:
all_done = asyncio.Future()
event_loop.run_until_complete(main(all_done))
finally:
event_loop.close()
这个回调只希望得到一个参数,即一个Future实例。要想为回调传递额外的参数,可以使用functools.partial()创建一个包装器。
运行结果: