DEV Community

Hitesh
Hitesh

Posted on

Async vs Await

Difference Between async and await

Both async and await are used in asynchronous programming in Python, enabling you to write non-blocking code while maintaining a synchronous-style syntax. Here's a simple breakdown of their roles:


1. async

  • Definition: The async keyword is used to declare an asynchronous function (also called a coroutine).
  • Purpose: Marks a function to be executed asynchronously and allows it to use await within its body.
  • Syntax:
  async def my_async_function():
      pass
Enter fullscreen mode Exit fullscreen mode
  • Behavior:
    • When called, an async function does not run immediately. Instead, it returns a coroutine object.
    • The coroutine needs to be awaited or scheduled to run using an event loop (e.g., via asyncio.run()).

Example:

async def greet():
    print("Hello!")
    await asyncio.sleep(1)  # Simulate asynchronous behavior
    print("Goodbye!")

# This alone won't run the function:
result = greet()  # Returns a coroutine object

# To actually execute it:
import asyncio
asyncio.run(greet())
Enter fullscreen mode Exit fullscreen mode

2. await

  • Definition: The await keyword pauses the execution of an async function until the awaited awaitable (e.g., coroutine, Task, or Future) completes.
  • Purpose: To "wait for" and retrieve the result of an asynchronous operation without blocking the entire program.
  • Syntax:
  async def my_async_function():
      await some_coroutine()
Enter fullscreen mode Exit fullscreen mode
  • Behavior:
    • Can only be used inside an async function.
    • Suspends the function’s execution, freeing the event loop to handle other tasks until the awaited operation finishes.

Example:

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)  # Simulates a network call
    print("Data fetched!")

async def main():
    print("Starting...")
    await fetch_data()  # Waits for `fetch_data` to complete
    print("Done!")

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Key Differences

Aspect async await
Purpose Declares a function as asynchronous. Waits for the result of an awaitable.
Placement Before the def keyword to define a coroutine. Inside an async function.
Execution Does not execute the function immediately. Pauses execution until the awaited task completes.
Dependency Defines a coroutine that can use await. Requires an async function to be valid.
Output Returns a coroutine object. Returns the result of the awaited operation.

Analogy

Think of async as preparing a worker who can handle tasks, and await as pausing to let the worker finish a specific task before proceeding.


Example Combining Both

import asyncio

async def download_file(file_name):
    print(f"Downloading {file_name}...")
    await asyncio.sleep(2)  # Simulates download time
    print(f"Downloaded {file_name}!")

async def main():
    print("Start")
    await download_file("file1.txt")
    print("End")

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. async declares the download_file and main functions as asynchronous.
  2. await inside main pauses execution until download_file completes.

Top comments (0)