Sobes.tech
Junior — Senior

Understanding the order of coroutine execution in asyncio

livecode

Task condition

Analyze the order in which messages are printed. Explain why, when running the script below, the output will be: 1, 3, 2.

import asyncio

async def task_one():
    await asyncio.sleep(10000000)
    print('1')
    return result

async def task_two():
    await asyncio.sleep(1)
    print('2')

async def run_all():
    await task_one()
    print('3')
    await task_two()

asyncio.run(run_all())

Note how await blocks the further execution of the current coroutine until the called one completes, but does not stop the entire event loop. This determines the order of the lines appearing in the console.

Understanding the order of coroutine execution in… - sobes.tech