Home > OS >  Why does 'await' break from the local function when called from main()?
Why does 'await' break from the local function when called from main()?

Time:02-15

I am new to asynchronous programming, and while I understand most concepts, there is one relating to the inner runnings of 'await' that I don't quite understand.

Consider the following:

import asyncio

async def foo():
    print('start fetching')
    await asyncio.sleep(2)
    print('done fetcihng')

async def main():
    task1 = asyncio.create_task(foo())

asyncio.run(main())

Output: start fetching

vs.

async def foo():
    print('start fetching')
    print('done fetcihng')

async def main():
    task1 = asyncio.create_task(foo())

asyncio.run(main())

Output: start fetching followed by done fetching

Perhaps it is my understanding of await, which I do understand insofar that we can use it to pause (2 seconds in the case above), or await for functions to fully finish running before any further code is run.

But for the first example above, why does await cause 'done fetching' to not run??

CodePudding user response:

asyncio.create_task schedules an awaitable on the event loop and returns immediately, so you are actually exiting the main function (and closing the event loop) before the task is able to finish

you need to change main to either

async def main():
    task1 = asyncio.create_task(foo())
    await task1

or

async def main():
    await foo()

creating a task first (the former) is useful in many cases, but they all involve situations where the event loop will outlast the task, e.g. a long running server, otherwise you should just await the coroutine directly like the latter

  • Related