forked from ProtonMail/go-proton-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
future.go
92 lines (69 loc) · 1.53 KB
/
future.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package proton
import (
"github.com/ProtonMail/gluon/async"
)
type Future[T any] struct {
resCh chan res[T]
panicHandler async.PanicHandler
}
type res[T any] struct {
val T
err error
}
func NewFuture[T any](panicHandler async.PanicHandler, fn func() (T, error)) *Future[T] {
resCh := make(chan res[T])
job := &Future[T]{
resCh: resCh,
panicHandler: panicHandler,
}
go func() {
defer async.HandlePanic(job.panicHandler)
val, err := fn()
resCh <- res[T]{val: val, err: err}
}()
return job
}
func (job *Future[T]) Then(fn func(T, error)) {
go func() {
defer async.HandlePanic(job.panicHandler)
res := <-job.resCh
fn(res.val, res.err)
}()
}
func (job *Future[T]) Get() (T, error) {
res := <-job.resCh
return res.val, res.err
}
type Group[T any] struct {
futures []*Future[T]
panicHandler async.PanicHandler
}
func NewGroup[T any](panicHandler async.PanicHandler) *Group[T] {
return &Group[T]{panicHandler: panicHandler}
}
func (group *Group[T]) Add(fn func() (T, error)) {
group.futures = append(group.futures, NewFuture(group.panicHandler, fn))
}
func (group *Group[T]) Result() ([]T, error) {
var out []T
for _, future := range group.futures {
res, err := future.Get()
if err != nil {
return nil, err
}
out = append(out, res)
}
return out, nil
}
func (group *Group[T]) ForEach(fn func(T) error) error {
for _, future := range group.futures {
res, err := future.Get()
if err != nil {
return err
}
if err := fn(res); err != nil {
return err
}
}
return nil
}