콜백 기반의 비동기 함수를 aync/await로 변경하는 목적
func asyncLoadData() async throws -> String {
try await withCheckedThrowingContinuation { continuation in
loadData { result in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
.
.
Task {
do {
let message = try await asyncLoadData()
print(message)
} catch {
print("❌ Error:", error)
}
}
응답이 도착한 시점에 resume 메서드를 통해 결과를 처리
func resume(returning value: sending T)func resume(throwing error: E)func resume(with result: sending Result<T, E>)불가피하게 Delegate을 통해 비동기 응답을 받을 경우에 유용하게 사용될 수 있음
class SomeService: SomeDelegate {
private var _continuation: CheckedContinuation<Data, Error>?
private func call() async -> Data {
return withCheckedThrowingContinuation { continuation in
_continuation = continuation
// API Call
someApi().load
}
}
// Delagte 응답
func loaded(let data: Data?, let error: Error?) {
if let data = data {
_continuation?.resume(returning: data)
} else if let error = error {
_continuation?.resume(throwing: error)
}
_continuation = nil
}
}
let result = try? await SomeService().call()
중요 You must call a resume method exactly once on every execution path throughout the program.
https://developer.apple.com/documentation/swift/checkedcontinuation