-1

I have the following code :

async def async_function():
    await some_function()


# TODO : Doesn't work
def sync_function():
    for i in range (100):
        async_function()

In the past I had no loop in sync_function, so I managed to call async_function using asyncio.run(). Now that I have a this for loop, I don't find the proper way to handle my asynchronous function.

The current code throws the following warning

RuntimeWarning: coroutine 'async_function' was never awaited

And part of the logic in it is not done during runtime.

What would be the good way to do this ?

1
  • 1
    You can move the loop to an async function and await the async_function (recommended) or you can call asyncio.run as before but in the loop (should work but isn't efficient). Commented Jan 5, 2024 at 15:54

1 Answer 1

1

You can use asyncio tasks (https://docs.python.org/3/library/asyncio-task.html). This is a working example:

import asyncio


async def async_function(i):
    """ dummy code """
    print("Hi from", i) 
    await asyncio.sleep(1)


def sync_function():
    for i in range(100):
        loop = asyncio.get_event_loop() # get asyncio loop
        loop.create_task(async_function(i))  # schedule task

    asyncio.get_event_loop().run_until_complete(asyncio.gather())  # run the asyncio.gather function, who's role is to run all scheduled tasks.


sync_function()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.