问题描述
我有2个函数:第一个函数def_a
是异步函数,第二个函数def_b
是常规函数,并以def_a
的结果作为add_done_callback
的回调进行调用功能.
I have 2 functions: The first one, def_a
, is an asynchronous function and the second one is def_b
which is a regular function and called with the result of def_a
as a callback with the add_done_callback
function.
我的代码如下:
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
也变得异步时,问题开始了.现在看起来像这样:
The problem began when also the second function, def_b
, became asynchronous. Now it looks like this:
async def def_b(result):
next_number = result.result()
# some asynchronous work on the next_number
print(next_number + 1)
但是现在我不能将其提供给add_done_callback
函数,因为它不是常规函数.
But now I can not provide it to the add_done_callback
function, because it's not a regular function.
我的问题是-如果def_b
是异步的,是否可以以及如何向add_done_callback
函数提供def_b
?
My question is- Is it possible and how can I provide def_b
to the add_done_callback
function if def_b
is asynchronous?
推荐答案
add_done_callback
被认为是低级"接口.使用协同程序时,您可以将其链接在许多方面,例如:
add_done_callback
is considered a "low level" interface. When working with coroutines, you can chain them in many ways, for example:
import asyncio
async 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 + 1
async def add_success_callback(fut, callback):
result = await fut
await callback(result)
return result
loop = 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()
会引发异常).
Keep in mind add_done_callback
will still call the callback if your future raises an exception (but calling result.result()
will raise it).
这篇关于带有异步def的python asyncio add_done_callback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!