Use errgroup to run multiple goroutines concurrently, wait for them to finish, and propagate the first error that occurs.
package main
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
"time"
)
func main() {
ctx := context.Background()
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < 3; i++ {
i := i // capture loop variable
g.Go(func() error {
time.Sleep(100 * time.Millisecond)
if i == 1 {
return fmt.Errorf("task %d failed", i)
}
fmt.Printf("task %d done\n", i)
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Println("Error:", err)
}
}