Cancel goroutines on first error using errgroup

The context handling in getData has no effect, once the goroutines are up and running.

The context handling should be moved into any function that potentially blocks, and ensure any blocking operations are bound to the context:

func fetch(ctx context.Context, n int, fail bool) (string, error) {

    // time.Sleep(time.Duration(n) * time.Second) 

    // sleep blocks - but cannot be context canceled...

    // ... use a time.Ticker channel-based read instead:

    select {
    case <-time.After(time.Duration(n) * time.Second):
        // sleep finished uninterrupted

    case <-ctx.Done():
        return "", ctx.Err()
    }

    if fail {
        return "", errors.New("an error")
    } else {
        return "Hello", nil
    }
}

https://play.golang.org/p/kGjmmAlGsG6

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top