I am just starting to learn about asynchronous programming, in particular the async and await syntax and usage of the asyncio module.
My question is regarding the output of the following code:
import asyncio async def foo(): print('start fetching') await asyncio.sleep(2) print('done fetching') return {'data':1} async def boo(): for i in range(10): print(i) await asyncio.sleep(0.25) async def main(): task1 = asyncio.create_task(foo()) task2 = asyncio.create_task(boo()) asyncio.run(main()) The output that I get is:
start fetching 0 While I understand what each individual part of the code does, I can't understand why only two lines of the code is being outputted. Here is my understanding:
- We start with
task1and printstart fetching. - Then we hit the await for 2 seconds.
- In these two seconds doesn't this give
task2the opportunity to do its execution for 2 seconds, so 0-8 will be printed? - Then I also don't see why we don't continue executing the function
foo()? – i.e.print('done fetching')?
await asyncio.gather(task1, task2)at the end ofmain.