Junior — Middle
What is the purpose of the 'await' operator in asynchronous programming?
sobes.tech AI
Answer from AI
The await operator in asynchronous programming in Python is used to suspend the execution of a coroutine until the asynchronous operation, which returns an awaitable object (such as another coroutine or Future), completes. This allows writing asynchronous code that looks like synchronous code, simplifying reading and maintenance.
Example:
import asyncio
async def fetch_data():
await asyncio.sleep(1) # simulate asynchronous operation
return 'Data received'
async def main():
result = await fetch_data() # execution pauses until fetch_data completes
print(result)
asyncio.run(main())
Here, await makes main wait for fetch_data to finish without blocking the execution thread.