【发布时间】:2017-11-04 19:43:37
【问题描述】:
我有 2 个函数:第一个,def_a,是一个异步函数,第二个是 def_b,它是一个常规函数,并以 def_a 的结果作为回调函数调用 add_done_callback功能。
我的代码如下所示:
import asyncio
def def_b(result):
next_number = result.result()
# some work on the next_number
print(next_number + 1)
async def def_a(number):
await some_async_work(number)
return number + 1
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(def_a(1))
task.add_done_callback(def_b)
response = loop.run_until_complete(task)
loop.close()
而且效果很好。
当第二个函数def_b 变得异步时,问题就开始了。现在看起来像这样:
async def def_b(result):
next_number = result.result()
# some asynchronous work on the next_number
print(next_number + 1)
但现在我无法将它提供给add_done_callback 函数,因为它不是常规函数。
我的问题是 - 如果def_b 是异步的,是否有可能以及如何将def_b 提供给add_done_callback 函数?
【问题讨论】:
标签: python python-3.x async-await python-asyncio coroutine