Sobes.tech
Junior — Middle

Is it possible to implement a custom wrapper for methods with completion handlers using async/await syntax?

sobes.tech AI

Answer from AI

Yes, you can create a custom wrapper for methods with a completion handler using async/await, applying the constructs with withCheckedContinuation or withUnsafeContinuation. This allows transforming a callback-oriented API into an asynchronous one, convenient for use with async/await.

Example in Swift:

func fetchDataAsync() async throws -> Data {
    return try await withCheckedThrowingContinuation { continuation in
        fetchData { result in
            switch result {
            case .success(let data):
                continuation.resume(returning: data)
            case .failure(let error):
                continuation.resume(throwing: error)
            }
        }
    }
}

Here, fetchData is a method with a completion handler, and fetchDataAsync is its async/await wrapper.

Is it possible to implement a custom wrapper for… - sobes.tech