python asyncio add_done_callback with async def

前端 未结 2 554
无人共我
无人共我 2020-12-24 08:27

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 r

2条回答
  •  醉话见心
    2020-12-24 08:54

    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()
    

    Keep in mind add_done_callback will still call the callback if your future raises an exception (but calling result.result() will raise it).

提交回复
热议问题