gpt4 book ai didi

swift - 在 Swift 中链接 promise 以初始化自定义对象

转载 作者:行者123 更新时间:2023-11-28 07:18:59 30 4
gpt4 key购买 nike

我在 Swift 中实现了 PromiseKit 以避免带有完成 block 的回调 hell 。我需要知道将 promise 链接在一起以初始化具有其他关联对象的自定义对象的最佳方法。例如,一个 Comment 对象附加了一个 User 对象。

首先,我从数据库中获取comments,它们在数据库结构中都有一个uid 属性。我最终想得到一组 comments,其中每个都有正确的用户附加到它,所以我可以同时加载 commentuser 数据。使用完成 block ,这一切似乎要容易得多,但我是一个完全 Promise 的菜鸟,所以 idk。

这是 Controller 中处理获取的代码

CommentsService.shared.fetchComments(withPostKey: postKey)
.then { comments -> Promise<[User]> in
let uids = comments.map({ $0.uid })
return UserService.shared.fetchUsers(withUids: uids)
}.done({ users in
// how to init Comment object with users now?
})
.catch { error in
print("DEBUG: Failed with error \(error)")
}

这是评论获取功能:

func fetchComments(withPostKey postKey: String) -> Promise<[Comment]> {
return Promise { resolver in
REF_COMMENTS.child(postKey).observeSingleEvent(of: .value) { snapshot in
guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
let data = Array(dictionary.values)
do {
let comments = try FirebaseDecoder().decode([Comment].self, from: data)
resolver.fulfill(comments)
} catch let error {
resolver.reject(error)
}
}
}
}

这里是获取用户函数

func fetchUsers(withUids uids: [String]) -> Promise<[User]> {
var users = [User]()

return Promise { resolver in
uids.forEach { uid in
self.fetchUser(withUid: uid).done { user in
users.append(user)
guard users.count == uids.count else { return }
resolver.fulfill(users)
}.catch { error in
resolver.reject(error)
}
}
}
}

这里是评论对象:

struct Comment: Decodable {
let uid: String
let commentText: String
let creationDate: Date
var user: User?
}

这就是完成 block 的简单之处,开始认为 Promises 不值得吗?

func fetchComments(withPostKey postKey: String, completion: @escaping([Comment]) -> Void) {
var comments = [Comment]()
REF_COMMENTS.child(postKey).observe(.childAdded) { (snapshot) in

guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
guard let uid = dictionary["uid"] as? String else { return }

UserService.shared.fetchUser(withUid: uid, completion: { (user) in
let comment = Comment(user: user, dictionary: dictionary)
comments.append(comment)
completion(comments)
})
}
}

最佳答案

好的,我想我明白你想做什么了。问题是您需要与用户一起捕获评论,这样您就可以一起返回,然后再将它们组合起来。它应该看起来像这样:

CommentsService.shared.fetchComments(withPostKey: postKey)
.then { comments -> Promise<[Comment], [User]> in
let uids = comments.map({ $0.uid })
return UserService.shared.fetchUsers(withUids: uids)
.then { users in
return Promise<[Comment], [User]>(comments, users)
}
}.done({ combined in
let (comments, users) = combined
//Do combiney stuff here
})
.catch { error in
print("DEBUG: Failed with error \(error)")
}

转换是 [评论] -> [用户] -> ([评论], [用户]) -> [附加用户的评论]

关于swift - 在 Swift 中链接 promise 以初始化自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717244/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com