How to await a request that is returning a dictionary

Viewed 23

I'm trying to understand how can I use asyncio to execute some tasks that takes certain time to get their response, so I have the following structure


async def get_features(nbatch):
    """Do something to my batch"""
    print(f"doing {nbatch}")    
    features = await get_batch_result(nbatch)
    print(f"finishing {nbatch}")
    return features

async def get_them_all():

    nbatches = [1,2,3,4,5]
    return await asyncio.gather(*(get_features(nbatch) for nbatch in nbatches))
    
elements = asyncio.run(get_them_all())

get_batch_result is a time consuming blocking function, and when it is finished, it returns a dictionary and when it finished, there is an error that tells object dict can't be used in 'await' expression.

So, I would like to clarify if I only can use asyncrhonous calls if the awaitable function is non-blocking? and if so, is the multithread approach the one that could work in this case?.

0 Answers
Related