Skip to content

Instantly share code, notes, and snippets.

@mattbajorek
Last active September 26, 2022 22:34
Show Gist options
  • Save mattbajorek/55bc2b3da5cafe203102542de4a7372a to your computer and use it in GitHub Desktop.
Save mattbajorek/55bc2b3da5cafe203102542de4a7372a to your computer and use it in GitHub Desktop.
Example usage of AwaitAll
package main
import (
"errors"
"fmt"
"math/rand"
"strconv"
"sync"
"time"
)
type ExampleResponse struct {
data string
err error
}
func main() {
inputs := []int{3, 4, 5}
responses := AwaitAll(inputs, func(input int) ExampleResponse {
// Function can be sync or async as it is wrapped in a goroutine
// Mock request to server each with different lengths
randomTime := rand.Intn(5)
time.Sleep(time.Duration(randomTime) * time.Second)
// Error cannot be thrown, but must be in struct
var err error
if randomTime > 1 {
err = errors.New("Request was too slow")
}
return ExampleResponse{
data: strconv.Itoa(input),
err: err,
}
})
// responses will be = []ExampleResponse{
// {data: "3", err: error or nil},
// {data: "4", err: error or nil},
// {data: "5", err: error or nil},
// }
fmt.Println(responses)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment