📝 Add ExampleWithContext to example_test.go

This commit is contained in:
Dan Jones 2025-11-14 15:07:21 -06:00
commit 09ebfaefbe

View file

@ -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
}