Skip to content

Async/Await

In one line

async/await lets you write non-blocking concurrent code that looks like sequential code using coroutines.

In simple words

async/await is Python's syntax for cooperative concurrency. You mark a function with async def to make it a coroutine, and use await to pause it until an async operation completes.

While a coroutine is awaiting (e.g., waiting for network I/O), the event loop can run other coroutines. This is single-threaded concurrency — no threads, no GIL issues. It's ideal for I/O-bound work (web servers, API calls, file reads).

This is NOT parallelism — only one coroutine runs at a time. For CPU-bound parallelism, use multiprocessing.

Example

python
import asyncio

async def fetch_data(name, delay):
    print(f"Start {name}")
    await asyncio.sleep(delay)  # Non-blocking wait
    print(f"Done {name}")
    return f"result-{name}"

async def main():
    # Run concurrently — total time ~2s, not 5s
    results = await asyncio.gather(
        fetch_data("A", 2),
        fetch_data("B", 1),
        fetch_data("C", 2),
    )
    print(results)

asyncio.run(main())

asyncio.gather runs coroutines concurrently. While one awaits, others run — total time is max(delays), not sum.

Common confusions

  • Confused with: threading

    The difference: async/await is single-threaded cooperative concurrency — coroutines yield control voluntarily at await points. Threading is preemptive and uses OS threads with GIL contention. Use async for I/O-bound, threading for blocking libraries.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary