Is there an API for awaiting multiple async results at once? Something akin to asyncio.gather() in Python, Promise.all() in javascript, or when() in PromiseKit?
Replies
You can do this with a TaskGroup. Use async on the group to add all the individual tasks, then await the next result.
-
Here's the documentation for
TaskGroup:https://developer.apple.com/documentation/swift/taskgroup
-
The
nextdocumentation seems to suggest that it only awaits one of the child tasks, not all of them in parallel. I guess an empty for loop iterating over anyAsyncSequence, which uses the next() method, achieves the same thing with a little more boilerplate. After the for loop completes, all the tasks are guaranteed to have completed. In many cases, that's probably enough. -
I stand corrected.
TaskGroupseems like the way to go. But there's definitely an opportunity to build an api that removes some boilerplate (a la bluebirdjs.com):func<T> all(tasks: WhateverTaskType[]) async throws -> T[] { var arr: Array<T> = [] try await withThrowingTaskGroup(of: T.self) { group in for task in tasks { group.async(operation: task) } for try await val in group { arr.append(val) } } return arr }
I think you can async let to kick off the tasks and then await a tuple of results.