我刚刚更新到 Xcode 13.2.1,现在可以访问异步等待,并且我正在尝试找到可以从合并“转换”为异步等待的地方。
我想实现以下目标...
给定一个像...的类型
struct Person {
let name: String
func fetchAvatar(completion: @escaping (UIImage?) -> Void) {
// fetch the image from the web and pass it into the completion.
}
}
我目前有这样的功能......
func fetchAllTheAvatars(people: [Person], completion: ([UIImage]) -> Void) {
Publisher.MergeMany(
people.map { person in
Future<UIImage?, Never> { promise in
person.fetchAvatar { promise(.success($0)) }
}
}
)
.compactMap { $0 }
.collect()
.sink { completion($0) }
.store(in: &cancellables )
}
现在......在我看来,这可能是转向使用 async wait 和的一个很好的候选者AsyncSequence
或许...?!?但它不一定是理想的,我只是想了解如何使用它们。我已经习惯了async await
在 JS 和 TS 中,这似乎有点不同。 :D
我向我的 Person 添加了一个包装函数...
func fetchAvatar() async -> UIImage? {
await withCheckedContinuation { continuation in
fetchAvatar { image in
continuation.resume(returning: image)
}
}
}
但现在我陷入了如何更新我的fetchAllTheAvatars
功能。
func fetchAllTheAvatars(people: [Person]) async -> [UIImage] {
people.map { ...???... }
}
我在网上看到的所有地方似乎都在使用for await line in url.lines { ... }
但我还没有 AsyncSequence。我需要以某种方式“转换”我的非异步数组Person
进入一个AsyncSequence
of () -> Image?
.
那可能吗?我的处理方式完全错误吗?
Thanks