Concurrent Fetch Cancels On First Error
Launch goroutines per task and cancel every sibling through a shared context CancelFunc as soon as one fails, ending the whole batch early.
Code
package main
import (
"context"
"errors"
"fmt"
"sync"
)
func fetch(ctx context.Context, id string) (string, error) {
if id == "billing" {
return "", errors.New("upstream 503 for billing")
}
return "ok:" + id, nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ids := []string{"users", "billing", "orders"}
results := make([]string, len(ids))
var wg sync.WaitGroup
var firstErr error
var errOnce sync.Once
for i, id := range ids {
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-ctx.Done(): // 已有同伴失败:直接放弃
return
default:
}
res, err := fetch(ctx, id)
if err != nil {
errOnce.Do(func() {
firstErr = err
cancel() // 一处失败,全体取消
})
return
}
results[i] = res
}()
}
wg.Wait()
if firstErr != nil {
fmt.Println("aborted:", firstErr)
}
for i, res := range results {
fmt.Printf("%d: %q\n", i, res)
}
}What the code does
Count the functions fetch and main as the entire surface area of Concurrent Fetch Cancels On First Error.
A single loop drives the file — for i, id := range ids. Failures are values here: 1 site check err and decide instead of letting one propagate. Work is dispatched on a goroutine. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Caveats
- There is no dependency tree here — the platform is the whole dependency.
- The function reports failure by returning
error— callers branch on it before touching other results.
Applying it
Entry signature: func fetch(ctx context.Context, id string) (string, error)
The demo output is labeled (aborted:), so every line in the printed output names the step that produced it.
The entry point wires fetch together — run it once and the whole demo flows.
Statements that matter most here
func fetch(ctx context.Context, id string) (string, error) {
if id == "billing" {
return "", errors.New("upstream 503 for billing")
}
return "ok:" + id, nil
}
for i, res := range results {
fmt.Printf("%d: %q\n", i, res)
}
if err != nil {
errOnce.Do(func() {
firstErr = err
cancel() // 一处失败,全体取消
})
return
}
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- By return value: each fallible call hands back an `error`, checked at 1 place here.
- What does Concurrent Fetch Cancels On First Error print when run?
- Run it as a complete program — the output lines carry labels such as `aborted:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.