I'm new to async-await and this has been confusing me.
import asyncio# Step 1: Define an asynchronous functionasync def print_message(message, delay): await asyncio.sleep(delay) print(message)# Step 2: Define the main asynchronous functionasync def main(): # Step 3: Create tasks without gather() task1 = asyncio.create_task(print_message("Hello", 2)) task2 = asyncio.create_task(print_message("Async", 1)) task3 = asyncio.create_task(print_message("World", 3)) # Step 4: Await tasks individually await task1 await task2 await task3 print("does this print before tasks?")# Step 5: Run the main asynchronous function in an event loopif __name__ == "__main__": asyncio.run(main())
So here in the main
coroutine, three asynchronous tasks are created and handed off to the event loop.And these tasks are awaited
in the same order, i.e. task1, task2, and task3.
Logically, since task2
has lower delay this Async
will get displayed earlier.
But I thought await
keyword will hold the execution of task1 before it can move further down to task2 and task3.
So my expectation was that the prints will also be in the same order irrespective of the delay value.
Also finally I've added a print in the
main
itself after awaits.So while these awaits are holding, shouldn't this print be executed?