Skip to content

Instantly share code, notes, and snippets.

@alfianlosari
Created May 31, 2021 07:39
Show Gist options
  • Save alfianlosari/b3ae3805f9058f59db6323fb8a9ecd8a to your computer and use it in GitHub Desktop.
Save alfianlosari/b3ae3805f9058f59db6323fb8a9ecd8a to your computer and use it in GitHub Desktop.
Fetch API GroupTask
// 1
func fetchAPIGroup<D: Decodable>(urls: [URL]) async throws -> [D] {
// 2
try await withThrowingTaskGroup(of: D.self) { (group) in
// 3
for url in urls {
group.async {
let data = try Data(contentsOf: url)
let decodedData = try JSONDecoder().decode(D.self, from: data)
return decodedData
}
}
// 4
var results = [D]()
for try await result in group {
results.append(result)
}
return results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment