0

How does "await" make code flow in Python? This is the code to clear my question

import asyncio

async def io_related(name):
    print(f'{name} started')
    await asyncio.sleep(0.1)
    print(f'{name} finished')


async def main():
    await asyncio.gather(
        io_related('1'),
        io_related('2'),
        io_related('3'),
        io_related('4'),
    )

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

and I got this output:

"1 started

2 started

3 started

4 started

1 finished

3 finished

2 finished

4 finished"

Why "3" finished before "2" ?. How does the code flow? I tried putting "1", "2", "3" in the "await asyncio.gather". It works as I expected but after the item "4", the order of things "finished" is messy terribly.

1
  • Why is this behavior unexpected? Are you aware of the purpose of asynchronous programming? Commented Mar 19, 2020 at 0:33

1 Answer 1

2

This is a question about how threading/asynchronous programming works. Async methods will all fire off at the same time, but finish whenever the data gets back.

The await here is just the keyword saying, "hey wait until all these come back before moving on".

So think of it more like loading webpages. If you call up google.com, microsoft.com, netflix.com and stackoverflow.com all at the same time, it can be reasonably expected that they might not return the page in the same order as you called them. That would depend on several things outside the scope of this question.

The key point here is that when you start using asynchronous methods, you cannot expect the results to come back in the order you called them.

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

1 Comment

Thank you. I got it. It's very helpful

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.