📝 Add ExampleWithContext to example_test.go
This commit is contained in:
parent
09feb51213
commit
09ebfaefbe
1 changed files with 48 additions and 0 deletions
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue