Python asyncio function call inside loop

Viewed 105

I have a server and client where multiple clients will be connecting to multiple server and does something. I want to make client connection to server async.

clients = [1,2,3]
for c in clients:
  connect_to_server()

right now the above code connects to server but waits for first iteration to be executed and then second. how to make it async function call to connect_to_server() method so that second iteration will not wait for first to be executed ? And which function has to be async either connect_to_server or for loop function and which has to be awaiting ?


def connect_to_server(client_id):
    print(client_id)
    time.sleep(3)


async def main():
    clients = [1, 2, 3, 4]
    for client in clients:
       await connect_to_server(client)

asyncio.run(main())
1 Answers

Here wrap the code you want to be async in an async function,

import asyncio

async def main():

    clients = [1,2,3]

    for c in clients:
        await connect_to_server()

asyncio.run(main())

Explaination : here asyncio calls your async "MAIN" function and "AWAIT" in the function makes the process proceed to the next iteration without waiting for connect_to_server() function to finish !

Related