From 06c15f8250ffddb3d9730fd2cc6abfb4a5151f7b Mon Sep 17 00:00:00 2001 From: Dan Jones Date: Thu, 13 Nov 2025 17:07:55 -0600 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20examples=20for=20WaitErr=20me?= =?UTF-8?q?thods?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example_test.go | 90 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 example_test.go diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..3246ddd --- /dev/null +++ b/example_test.go @@ -0,0 +1,90 @@ +package waiterr_test + +import ( + "errors" + "fmt" + "time" + + "codeberg.org/danjones000/waiterr" +) + +func Example() { + we := new(waiterr.WaitErr) + + we.Go(func() error { + time.Sleep(100 * time.Millisecond) + fmt.Println("Goroutine 1 finished") + return nil + }) + + we.Go(func() error { + time.Sleep(50 * time.Millisecond) + fmt.Println("Goroutine 2 finished with an error") + return errors.New("something went wrong in goroutine 2") + }) + + we.Go(func() error { + time.Sleep(150 * time.Millisecond) + fmt.Println("Goroutine 3 finished") + return nil + }) + + // Wait for all goroutines and get all errors + if err := we.Wait(); err != nil { + fmt.Printf("All goroutines finished. Combined error:\n%v\n", err) + } + + // Output: + // Goroutine 2 finished with an error + // Goroutine 1 finished + // Goroutine 3 finished + // All goroutines finished. Combined error: + // something went wrong in goroutine 2 +} + +func ExampleWaitErr_WaitForError() { + we := new(waiterr.WaitErr) + we.Go(func() error { + time.Sleep(100 * time.Millisecond) + return errors.New("first error from we") + }) + we.Go(func() error { + time.Sleep(50 * time.Millisecond) + return errors.New("second error from we") + }) + + if err := we.WaitForError(); err != nil { + fmt.Printf("First error returned from we: %v\n", err) + } + + // Output: + // First error returned from we: second error from we + +} + +func ExampleWaitErr_Unwrap() { + we := new(waiterr.WaitErr) + we.Go(func() error { + time.Sleep(100 * time.Millisecond) + return errors.New("first error from we") + }) + we.Go(func() error { + time.Sleep(50 * time.Millisecond) + return errors.New("second error from we") + }) + we.Go(func() error { + time.Sleep(75 * time.Millisecond) + return nil + }) + + _ = we.Wait() + + errs := we.Unwrap() + for _, e := range errs { + fmt.Println(e) + } + + // Output: + // second error from we + // first error from we +}