我需要在执行下一个 (i + 1) 之前完成 performAsyncRequests-methods(对于每个 i)。我正在尝试这个:
let group = DispatchGroup()
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
for i in 0..<results.count {
group.enter()
print("\(i)-async started")
queue.addOperation {
print("Operation \(i) added")
self.performAsyncRequests(completion: { (result) in
print("Request \(i) completed")
group.leave()
})
}
}
group.notify(queue: .main) {
print("All requests completed")
self.reloadTableView()
}
但这会同时执行多个请求。感谢有人能指出我正确的方向。
最简单的解决方案是编写一个递归执行请求的例程,例如:
func performNextRequest(_ index: Int = 0) {
guard index < results.count else {
DispatchQueue.main.async {
// initiate whatever you want when this is done
self.reloadTableView()
}
return
}
performAsyncRequest(index) { [weak self] in
self?.performNextRequest(index + 1)
}
}
更优雅的解决方案是使用一些异步模式,例如异步Operation
子类或承诺。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句