Call a function Asynchronously from within a Loop and wait for the Results in Python
In this example, we will show you how to call a function asynchronously from within a loop and wait for the results using asyncio in Python.
Here in this example code, we are calling the time_taking_operation() function asynchronously from within a loop. The asyncio.gather() function collects all responses returned by time_taking_operation() function:
import asyncio import random async def time_taking_operation(item): print("operation started for : ", item) #multipying the item result = item * item #getting a random number from 0 to 100 time = random.randint(0,100) #making the function wait for the random period of time to fake real time consuming operation await asyncio.sleep(time) print("operation complete for : ", item) return result async def main(data_list): #looping through the list and calling time_taking_operation function coros = [time_taking_operation(item) for item in data_list] #waiting and collecting responses from each call to time_taking_operation function results = await asyncio.gather(*coros) return results if __name__ == "__main__": data_list = [1,2,3,4,5,6,7,8,9,10] loop = asyncio.get_event_loop() results = loop.run_until_complete(main(data_list)) print("Final results = ", results)
The output of the above code is as follows:
operation started for : 1 operation started for : 2 operation started for : 3 operation started for : 4 operation started for : 5 operation started for : 6 operation started for : 7 operation started for : 8 operation started for : 9 operation started for : 10 operation complete for : 8 operation complete for : 6 operation complete for : 9 operation complete for : 7 operation complete for : 3 operation complete for : 4 operation complete for : 2 operation complete for : 10 operation complete for : 1 operation complete for : 5 Final results = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]