Sobes.tech
Junior — Middle

How do you implement asynchronous operations using async/await?

sobes.tech AI

Answer from AI

In Python, the keywords async and await are used for asynchronous operations. async is used to declare an asynchronous function, and await is used inside such functions to wait for the result of an asynchronous operation. This allows the main thread not to block and to switch between tasks when one of them is waiting for an operation to complete (e.g., input/output).

Example:

import asyncio

async def fetch_data():
    print("Starting data load...")
    await asyncio.sleep(2)  # simulate an asynchronous operation
    print("Data loaded")
    return {'data': 123}

async def main():
    result = await fetch_data()
    print(f"Result: {result}")

asyncio.run(main())

Here, fetch_data is an asynchronous function that "sleeps" for 2 seconds without blocking execution. In main, we call it with await to wait for the result. asyncio.run starts the main event loop.