Force an async function to finish before next task

Viewed 595

I'm using a python API wrapper with async functions. I need to call the API several times and would like to override the async functionality by waiting for each task to complete before moving on to the next iteration.

import asyncio
loop = asyncio.get_event_loop()
for count in range(5):
    loop.create_task(main(count)) # Need this line to complete before next iteration
    time.sleep(60) # Hacky solution

Currently I'm just sleeping until I can assume main() is complete. How can I ensure main() never runs concurrently with itself?

1 Answers

To wait for the task to finish, use await. This requires an async function, which you can run using asyncio.run:

async def x():
    for count in range(5):
        await main(count)

asyncio.run(x())

If you want to do the same from top-level code, just call run_until_complete as many times as needed:

loop = asyncio.get_event_loop()
for count in range(5):
    loop.run_until_complete(main(count))
Related