Full Byte Developer.

Go without async await: channels and WaitGroup

Go skips async and await. Use goroutines with channels, WaitGroup, errgroup, and the pipelines pattern from the docs.

Published here · 4 sources

If you arrive from Python or JavaScript, you look for async and await in Go and come up empty. That is normal. Effective Go and the pipelines blog document goroutines plus channels, WaitGroup, and errgroup instead of colored async functions. Parent code blocks on Wait, a channel receive, or select. [4]

Related reading: Goroutines vs Python coroutines, Concurrency vs parallelism and Is Go slower than Rust?. Browse the dev-explainers topic.

Wait for a set of goroutines

sync.WaitGroup waits until a collection of goroutines finish. The package docs' contract is: Add the count, each goroutine calls Done, the parent calls Wait. [1]

bash
cat > /tmp/wg.go <<'EOF'
package main
import ("fmt"; "sync")
func main() {
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(n int) {
            defer wg.Done()
            fmt.Println(n)
        }(i)
    }
    wg.Wait()
}
EOF
go run /tmp/wg.go

Call Add before the goroutine starts, or you can race Wait. That detail is in the package documentation. [1]

Prefer errgroup when any error fails the batch

golang.org/x/sync/errgroup runs a group of goroutines and returns the first non-nil error. Use it when any failure should stop the batch. Pair it with context cancellation when later stages should abort. [2]

go
g, ctx := errgroup.WithContext(context.Background())
g.Go(func() error { return doA(ctx) })
g.Go(func() error { return doB(ctx) })
if err := g.Wait(); err != nil {
    // first error wins
}

Import path: golang.org/x/sync/errgroup. Keep the first error; do not invent a custom "collect all errors" unless you need that shape. [2]

Use channel pipelines for staged work

The Go blog post Go Concurrency Patterns: Pipelines and cancellation shows staged channel pipelines: each stage receives on an inbound channel, sends on an outbound channel, and respects cancellation. That is the idiomatic replacement for a long async/await chain when the work is a stream of values. [3]

Sketch from the pattern (read the blog for the full cancellation story):

go
func stage(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for v := range in {
            out <- v * 2
        }
    }()
    return out
}

Always decide who closes each channel. Leaking goroutines blocked on send is the common pipelines bug the post warns about. [3]

Pick the primitive that matches the job

JobPrimitive
Wait until N workers finishsync.WaitGroup [1]
Stop the batch on first errorerrgroup [2]
Stream values through stageschannel pipeline [3]
Start independent workgo f() [4]

There is still no await. Parent code blocks on Wait, channel receive, or select. See Goroutines vs Python coroutines when someone asks for a line-by-line async port. [4]

Failure checklist

  1. Wait before all Add calls: race; reorder
  2. Goroutine without Done / without channel close: hang
  3. Shared map without sync: data race; prefer channels or sync types
  4. Expecting go alone to cancel work: wire context into the pipeline [3]

Your next Go service review should name WaitGroup, errgroup, or a pipeline before anyone proposes adding an async runtime.

Send this to the teammate who keeps asking where await went in the Go code review.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

Why does Go have no async or await?

The language treats goroutines as the concurrent unit. Effective Go and the pipelines blog show composition with channels instead of colored async functions.

What is WaitGroup for?

sync.WaitGroup waits for a collection of goroutines to finish. Add before you start work, Done when a goroutine exits, Wait in the parent.

When do I use errgroup?

golang.org/x/sync/errgroup runs a group of goroutines and returns the first non-nil error. Use it when any failure should cancel or stop the batch.

Where do pipelines fit?

The Go blog post Go Concurrency Patterns: Pipelines and cancellation shows staged channel pipelines for streaming work between goroutines.

Sources

Next in this stack