Junior — Middle
What are the main methods of implementing asynchronous operations in programming?
sobes.tech AI
Answer from AI
The main methods of implementing asynchronous operations in programming include:
- Callbacks — a function is passed as a parameter and called after the operation completes.
- Promises — an object representing the result of an asynchronous operation, with
.then(),.catch()methods to handle the result or error. - Async/Await — syntactic sugar over promises, allowing asynchronous code to be written in a synchronous style using the
asyncandawaitkeywords. - Delegate and queue-based operations — often used in iOS, for example, GCD (Grand Central Dispatch) for thread management.
Example of using async/await in Swift:
func fetchData() async throws -> Data {
let url = URL(string: "https://example.com/data")!
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
These methods enable efficient task execution without blocking the main thread of the application.