3

I have a question.

I wrote a simple code that mimics http request:

from asyncio import sleep, run


async def get():
    print("Started get()")
    await sleep(3)
    print("Finished get()")


async def async_main():
    await get()
    await get()
    await get()


if __name__ == "__main__":
    run(async_main())

I expected that the result should be like:

Started get()
Started get()
Started get()
(No output, just wait 3 seconds)
Finished get()
Finished get()
Finished get()

But the result was:

Started get()
(No output, just wait 3 seconds)
Finished get()
Started get()
(No output, just wait 3 seconds)
Finished get()
Started get()
(No output, just wait 3 seconds)
Finished get()

Why is this happening?

2
  • 2
    Because you're awaiting them 1 by 1. You're looking for asyncio.gather. It'll be something like await asyncio.gather(get(), get(), get()) Commented Jan 8, 2022 at 3:35
  • TYSM @KonstantinK. ! It worked as I expected! Commented Jan 8, 2022 at 3:37

2 Answers 2

2

You need to schedule the coroutines, either explicitly using asyncio.create_task() or implicitly using asyncio.gather():

from asyncio import sleep, run


async def get():
    print("Started get()")
    await sleep(3)
    print("Finished get()")


async def async_main():
    tasks = [asyncio.create_task(get()), 
             asyncio.create_task(get()),
             asyncio.create_task(get())]  # Explicit
    await asyncio.gather(*tasks)

async def async_main(): # Option 2
    await asyncio.gather(get(), get(), get())  # Implicit

if __name__ == "__main__":
    run(async_main())
Sign up to request clarification or add additional context in comments.

Comments

2

just run the task asynchronously like below

async def async_main():
    await asyncio.gather(get(), get(), get())

if __name__ == "__main__":
    # run(async_main()) or
    asyncio.run(async_main())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.