Skip to content

Instantly share code, notes, and snippets.

@mattbajorek
Last active September 26, 2022 22:23
Show Gist options
  • Save mattbajorek/9aefb6c53b151b2b021ef84c83739d6e to your computer and use it in GitHub Desktop.
Save mattbajorek/9aefb6c53b151b2b021ef84c83739d6e to your computer and use it in GitHub Desktop.
AwaitAll will take a slice of inputs and will inject the input into the async func to run in parallel with the other inputs. Then function will wait until all of the responses are done and will return them in the same order of the inputs. The async function cannot throw an error and must return the error in the response.
func AwaitAll[Input any, Response any](sliceOfInputs []Input, asyncFunc func(Input) Response) []Response {
responses := make([]Response, len(sliceOfInputs))
var waitGroup sync.WaitGroup
for i, input := range sliceOfInputs {
waitGroup.Add(1)
go func(i int, input Input) {
responses[i] = asyncFunc(input)
waitGroup.Done()
}(i, input)
}
waitGroup.Wait()
return responses
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment