Lesson 47 / 47

Async Basics

Run I/O-bound work concurrently without threads, using async/await.

Why async?

async/await let a program work on other tasks while one is waiting — e.g. for a network response — instead of blocking everything.

A minimal example

An async def function is a coroutine. await pauses it at a slow operation; asyncio.run starts the whole thing.

import asyncio

async def fetch_data(name, delay):
    print(f"{name}: starting")
    await asyncio.sleep(delay)   # simulate I/O wait
    print(f"{name}: done")

async def main():
    await asyncio.gather(
        fetch_data("A", 2),
        fetch_data("B", 1),
    )

asyncio.run(main())

Output:

A: starting
B: starting
B: done
A: done