Codzy

Asynchronous programming: async and await

Asynchronous programming lets a program start a slow operation (a download, a network request…) and do something else while waiting, instead of being stuck. A function defined with async def is a coroutine; inside it, await waits for the result of another coroutine.

On your computer, you start the main coroutine with asyncio.run(main()), and asyncio.gather() runs several coroutines at the same time. In this browser, an event loop is already running, so we use a mini runner, run(), provided in the code, which drives the coroutine to the end.

import asyncio

async def fetch_price(item):
    await asyncio.sleep(0)
    return {"bread": 120, "milk": 90}[item]

async def main():
    bread = await fetch_price("bread")
    milk = await fetch_price("milk")
    return bread + milk

# On your computer: print(asyncio.run(main()))
# In this browser, an event loop is already running, so we use a mini runner:
def run(coro):
    while True:
        try:
            coro.send(None)
        except StopIteration as done:
            return done.value

print(run(main()), "cents")

Start the lesson