当我在循环的每次迭代中进行异步调用时,尝试使我的for循环同步。我有一种感觉,我需要以某种方式使用Grand Central Dispatch,但不确定。
func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
var results: [String] = []
for string in strings {
Service.shared.fetch(with: string, completion: { (result) in
results.append(result)
})
}
// this will run before asynchronous method in for-loop runs n times.
completion(results)
}
答案 0 :(得分:0)
您不需要使此循环同步。您真正想要的是在获得所有completion
时致电results
。您可以使用此解决方案(免费):
func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
var results: [String] = []
for string in strings {
Service.shared.fetch(with: string, completion: { (result) in
DispatchQueue.main.async {
results.append(result)
if results.count >= strings.count {
completion(results)
}
}
)
}
}