diff --git a/example_test.go b/example_test.go index 2f1c9cd..5e30d21 100644 --- a/example_test.go +++ b/example_test.go @@ -1,6 +1,7 @@ package waiterr_test import ( + "context" "errors" "fmt" "time" @@ -87,3 +88,50 @@ func ExampleWaitErr_Unwrap() { // second error from we // first error from we } + +func ExampleWithContext() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + we, ctx := waiterr.WithContext(ctx) + + we.Go(func() error { + select { + case <-time.After(100 * time.Millisecond): + fmt.Println("Goroutine 1 finished") + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + + we.Go(func() error { + select { + case <-time.After(50 * time.Millisecond): + fmt.Println("Goroutine 2 finished with an error") + return errors.New("something went wrong in goroutine 2") + case <-ctx.Done(): + return ctx.Err() + } + }) + + we.Go(func() error { + select { + case <-time.After(150 * time.Millisecond): + fmt.Println("Goroutine 3 finished") + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + + if err := we.Wait(); err != nil { + fmt.Printf("All goroutines finished. Combined error: %s\n", err) + } + + // Output: + // Goroutine 2 finished with an error + // All goroutines finished. Combined error: something went wrong in goroutine 2 + // context canceled + // context canceled +}