0

I wrote the following code:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

async def main():
  await write_after(1,'Hello...')
  await write_after(2,'...world')

asyncio.run(main())

As result I got:

begin
Hello...
begin
...world

with pauses right after begins. I was wondering why result isn't:

begin
begin
Hello...
...world

like executing program that uses tasks.

1
  • 1
    Then it wouldn't be possible to call multiple async functions in an ordered way, one after another. Commented Jul 26, 2020 at 20:46

2 Answers 2

1

Basically what's happening is you're waiting for the first result to finish, then starting the second function call and waiting for that result. I think what you're expecting is something like this:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

async def main():
  await asyncio.gather(
    write_after(1,'Hello...'),
    write_after(2,'...world')
  )

asyncio.run(main())

This will launch both coroutines concurrently and wait for the results of each. The result will be:

begin
begin
Hello...
...world
Sign up to request clarification or add additional context in comments.

Comments

1

@kingkupps analysis is correct. Unfortuantely, myy asyncio module has no run method (Python 3.7), so as an alternative:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(
        asyncio.gather(
            write_after(1, 'Hello'),
            write_after(2, '...world')
        )
    )

main()

Prints:

begin
begin
Hello
...world

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.