问题
Trying to make my for loop behave synchronously when I am making an asynchronous call in each iteration of the loop. I have a feeling I will need to use Grand Central Dispatch in some way but not sure.
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)
}
回答1:
You don't need to make this loop synchronous. What you really want is to call completion
when you will get all results
. You can use this solution (for free):
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)
}
}
)
}
}
来源:https://stackoverflow.com/questions/48254073/calling-asynchronous-method-inside-for-loop