Sobes.tech
Junior — Middle

Can you explain how the await keyword works in an asynchronous program?

sobes.tech AI

Answer from AI

The await keyword in Python is used inside asynchronous functions to pause execution until an asynchronous operation (such as a coroutine, Future, or Task) completes. This allows the thread not to be blocked and to efficiently utilize waiting time.

When the interpreter encounters await, it:

  • Yields control back to the event loop, allowing other tasks to run.
  • Waits for the asynchronous operation to complete.
  • After completion, continues executing the function with the result of the operation.

Example:

import asyncio

async def fetch_data():
    await asyncio.sleep(1)  # simulate delay
    return "Data received"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

Here, await allows the program not to block while waiting for sleep, and to continue working when the delay is over.