[swift] Promise 체인과 연속적인 비동기 작업 처리

비동기 프로그래밍은 현대 프로그래밍에서 매우 중요한 부분입니다. 이는 네트워크 요청, 파일 다운로드, 데이터베이스 접근 등과 같은 작업에 사용됩니다. Swift에서 비동기 작업을 처리하는 방법 중 하나는 Promise 체인을 사용하는 것입니다.

Promise 체인이란?

Promise는 비동기 작업의 결과를 나타내는 객체입니다. 이는 작업이 완료되었을 때 결과를 포함하고, 작업이 실패했을 때 에러를 포함합니다. Promise는 then, catch, finally와 같은 메소드를 제공하여 결과나 에러를 처리할 수 있습니다.

Promise 체인은 여러 비동기 작업을 연속적으로 실행할 수 있도록 도와줍니다. 즉, 첫 번째 작업이 완료되면 다음 작업을 실행하고, 그 결과를 가지고 또 다음 작업을 실행하는 식으로 작업이 이어집니다.

예제 코드

func fetchUserData() -> Promise<User> {
    return URLSession.shared.dataTask(.promise, with: url)
        .map { $0.data }
        .decode(type: User.self, decoder: JSONDecoder())
}

func fetchPosts() -> Promise<[Post]> {
    return URLSession.shared.dataTask(.promise, with: url)
        .map { $0.data }
        .decode(type: [Post].self, decoder: JSONDecoder())
}

func fetchComments(postId: Int) -> Promise<[Comment]> {
    let url = URL(string: "https://api.example.com/posts/\(postId)/comments")!
    return URLSession.shared.dataTask(.promise, with: url)
        .map { $0.data }
        .decode(type: [Comment].self, decoder: JSONDecoder())
}

위의 코드에서 fetchUserData, fetchPosts, fetchComments 함수는 각각 사용자 정보, 게시물 정보, 댓글 정보를 비동기적으로 가져오는 함수입니다. 이 함수들은 URLSession을 사용하여 비동기 작업을 수행하고, 결과를 Promise로 반환합니다.

이제 Promise 체인을 사용하여 이러한 함수들을 연속적으로 실행해보겠습니다.

fetchUserData()
    .then { user in
        print("User data: \(user)")
        return fetchPosts()
    }
    .then { posts in
        print("Post data: \(posts)")
        return fetchComments(postId: posts.first?.id ?? 0)
    }
    .then { comments in
        print("Comments data: \(comments)")
    }
    .catch { error in
        print("Error: \(error)")
    }

위의 코드는 다음과 같이 작동합니다:

  1. fetchUserData 함수를 실행하고 결과를 받습니다. 이후 then 블록에서 결과를 처리합니다.
  2. fetchPosts 함수를 실행하고 결과를 받습니다. 이후 then 블록에서 결과를 처리합니다.
  3. fetchComments 함수를 실행하고 결과를 받습니다. 이후 then 블록에서 결과를 처리합니다.
  4. 작업 중에 에러가 발생하면 catch 블록에서 에러를 처리합니다.

이렇게 Promise 체인을 사용하면 비동기 작업을 간편하게 처리할 수 있습니다. 코드가 간결하며 비동기적인 작업이 순차적으로 이루어져 결과를 확실히 처리할 수 있습니다.

참고 자료