Skip to content

Instantly share code, notes, and snippets.

@AndrewBarba
Created June 20, 2021 03:18
Show Gist options
  • Save AndrewBarba/89c81ab1e98626e29c728eccd9cf1219 to your computer and use it in GitHub Desktop.
Save AndrewBarba/89c81ab1e98626e29c728eccd9cf1219 to your computer and use it in GitHub Desktop.
Concurrent async version of map on any Sequence
extension Sequence {
func mapAsync<T>(_ handler: @escaping (Element) async -> T) async -> [T] {
return await withTaskGroup(of: (Int, T).self) { group in
var results: [Int: T] = [:]
for (index, item) in self.enumerated() {
group.async { (index, await handler(item)) }
}
for await (index, transformed) in group {
results[index] = transformed
}
return self.enumerated().map { index, _ in results[index]! }
}
}
}
@AndrewBarba
Copy link
Author

AndrewBarba commented Jun 20, 2021

// Array of user ids
let ids = [...]

// Concurrently retrieve all users
let users = await ids.mapAsync { id in
  return await getUserAsync(id)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment