python asyncio add_done_callback with async def

前端 未结 2 547
无人共我
无人共我 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:43

    This only works for one future job, if you have multiple async jobs, they will blocks each other, a better way is using asyncio.as_comleted() to iterate future list:

    import asyncio
    
    async def __after_done_callback(future_result):
        # await for something...
        pass
    
    async def __future_job(number):
        await some_async_work(number)
        return number + 1
    
    loop = asyncio.get_event_loop()
    tasks = [asyncio.ensure_future(__future_job(x)) for x in range(100)]  # create 100 future jobs
    
    for f in asyncio.as_completed(tasks):
        result = await f
        await __after_done_callback(result)
    
    loop.close()
    

提交回复
热议问题