forked from earthboundkid/flowmatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
do.go
59 lines (54 loc) · 1.07 KB
/
do.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package flowmatic
import (
"errors"
"sync"
)
// Do runs each task concurrently
// and waits for them all to finish.
// Errors returned by tasks do not cancel execution,
// but are joined into a multierror return value.
// If a task panics during execution,
// a panic will be caught and rethrown in the parent Goroutine.
func Do(tasks ...func() error) error {
type result struct {
err error
panic any
}
var wg sync.WaitGroup
errch := make(chan result, len(tasks))
wg.Add(len(tasks))
for i := range tasks {
fn := tasks[i]
go func() {
defer wg.Done()
defer func() {
if panicVal := recover(); panicVal != nil {
errch <- result{panic: panicVal}
}
}()
errch <- result{err: fn()}
}()
}
go func() {
wg.Wait()
close(errch)
}()
var (
panicVal any
errs []error
)
for res := range errch {
switch {
case res.err == nil && res.panic == nil:
continue
case res.panic != nil:
panicVal = res.panic
case res.err != nil:
errs = append(errs, res.err)
}
}
if panicVal != nil {
panic(panicVal)
}
return errors.Join(errs...)
}