i am a little new to asyncio in python. I was trying to run this simple code but i don't know why i am getting this unexpected output.
What i did is that, in outer function, i created async tasks and stored it in an array tasks. Before awaiting on these tasks i wrote a print statement print("outer") that should run in every iteration. And inside the task i wrote another print statement print("inner") in inner function. But some how i am getting some unexpected output.
Here's the code -
import asyncio
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(outer(loop))
loop.close()
async def outer(loop):
tasks = []
for i in range(0, 5):
tasks.append(loop.create_task(inner()))
for task in tasks:
print("outer")
await task
async def inner():
print("inner")
await asyncio.sleep(0.5)
if __name__ == '__main__':
main()
Here's the output -
outer
inner
inner
inner
inner
inner
outer
outer
outer
outer
My Expected output was -
outer
inner
outer
inner
outer
inner
outer
inner
outer
inner
Why all the inner are printing before outer. What is the correct execution flow of asyncio. Thanks in advance.