Calls to a async code must be awaited somewhere.
Calling an async function returns a coroutine object.
This can be send to the event loop or awaited.
To gather coroutines, you can use
Calling an async function returns a coroutine object.
This can be send to the event loop or awaited.
To gather coroutines, you can use
asyncio.gather(*coros)
.import random import asyncio import time class A: def __init__(self): self.number = random.random() async def my_method(self): # await for the coroutine await asyncio.sleep(1) # is later collected by asyncio.gather return 'Hello World' async def worker(tasks): # create the coroutines by calling the async method # don't await for them, gather is doing this coros = [task.my_method() for task in tasks] # gather runs all tasks together asynchronous # and returns the return values as a list # await is needed here, to run the # gather function return await asyncio.gather(*coros) # create some classes objects = [A() for _ in range(3)] # now a list with 20 instances of A coro = worker(objects) # code is currently not running loop = asyncio.get_event_loop() # this runs the asynchronous code # in the event loop # after is has been finished all tasks # the method returns the results # in this case a list, because the use of gather results = loop.run_until_complete(coro) print(results) # another example with one task my_a = A() result = loop.run_until_complete(my_a.my_method()) # this time result is a string print(result) # here synchronous codeMaybe you have to put return await in different lines. I use Python 3.7.
return await asyncio.gather(*coros)
result = await asyncio.gather(*coros) return results
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!