Junior — Middle
What is the main purpose of the async/await construct in programming?
sobes.tech AI
Answer from AI
The Kotlin coroutine mechanism is used for managing asynchronous tasks, allowing writing code that looks synchronous but executes asynchronously.
Main purposes:
- Handling asynchronous operations:
asyncmarks a function as asynchronous, returning acoroutineobject. - Waiting for results:
awaitsuspends the function until the asynchronous operation completes, without blocking the thread.
This enables executing long-running operations (like network requests, file reading) without blocking the main thread, while maintaining readability.
Example in Python:
import asyncio
async def fetch_data():
await asyncio.sleep(1) # simulate delay
return 'data'
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Here, await allows waiting for fetch_data result without blocking the entire application.