Junior — Middle
Can you explain what the keyword 'await' means in programming and how it is used in asynchronous operations?
sobes.tech AI
Answer from AI
The await keyword in Python is used inside asynchronous functions (declared with async def) to suspend the execution of the current coroutine until an asynchronous operation that returns an awaitable object (such as another coroutine or Future) completes. This allows writing asynchronous code that looks like synchronous code, simplifying handling of I/O operations, network requests, and other long-running tasks.
Example usage:
import asyncio
async def fetch_data():
print("Starting data load...")
await asyncio.sleep(2) # simulate asynchronous delay
print("Data loaded")
return {'data': 123}
async def main():
result = await fetch_data() # wait for fetch_data to complete
print(result)
asyncio.run(main())
Here, await makes main wait until fetch_data finishes, without blocking the entire thread.