liveBook · Manning

Errgroup.Group.Wait

As explained in 100 Go Mistakes and How to Avoid Them

errgroup.Group.Wait blocks until all goroutines in an errgroup.Group complete and returns the first non-nil error, if any.

A common mistake is using sync.WaitGroup without a clear error path. errgroup.Group.Wait blocks until every g.Go function completes, then returns the first non-nil error; errgroup also coordinates cancellation through its context. section 9.13

Replace manual error aggregation

With a plain WaitGroup, each goroutine must publish errors through a shared slice, mutex, or channel, and the parent must aggregate them afterward. With errgroup, return the error from the goroutine and check it once: `if err := g.Wait(); err != nil { return nil, err }`. Return the collected results only after Wait succeeds. section 9.13

func handler(ctx context.Context, circles []Circle) ([]Result, error) {
    results := make([]Result, len(circles))
    g, ctx := errgroup.WithContext(ctx)      #1
 
    for i, circle := range circles {
        i := i
        circle := circle
        g.Go(func() error {                  #2
            result, err := foo(ctx, circle)
            if err != nil {
                return err
            }
            results[i] = result
            return nil
        })
    }
 
    if err := g.Wait(); err != nil {         #3
        return nil, err
    }
    return results, nil
}

Trace the complete handler pattern: create an errgroup with context, start work with g.Go, return errors from workers, and handle the result of g.Wait. section 9.13

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Shows the replacement for manual error aggregation but does not detail Wait's internal implementation.
Examples
Uses a handler that calls foo concurrently for indexed Circle values and stores Result values in a shared slice.
What it assumes
Assumes familiarity with goroutines, WaitGroup synchronization, contexts, and concurrent result collection.
What you can do after
Apply it via golang.org/x/sync/errgroup to wait for workers and return an error without custom aggregation.
How it connects
Connects goroutines, context cancellation, sync.WaitGroup, shared results, and error propagation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.