-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathasync.go
122 lines (104 loc) · 1.88 KB
/
async.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package async
type AsyncState int
const (
PENDING AsyncState = iota
FULFILLED
REJECTED
)
type AsyncTask[V any] struct {
valueCh chan V
errCh chan any
Value V
Err any
State AsyncState
}
func Async[V any](f func() V) func() *AsyncTask[V] {
exec := func() *AsyncTask[V] {
task := &AsyncTask[V]{
valueCh: make(chan V, 1),
errCh: make(chan any, 1),
State: PENDING,
}
go func() {
var result V
defer func() {
if e := recover(); e == nil {
task.State = FULFILLED
task.Value = result
task.valueCh <- result
} else {
task.State = REJECTED
task.Err = e
task.errCh <- e
}
close(task.valueCh)
close(task.errCh)
}()
result = f()
}()
return task
}
return exec
}
func Await[V any](t *AsyncTask[V]) (V, any) {
var value V
var err any
switch t.State {
default:
select {
case err = <-t.errCh:
return value, err
case value = <-t.valueCh:
return value, err
}
case FULFILLED:
return t.Value, err
case REJECTED:
return value, t.Err
}
}
func All[V any](fs []func() V) *AsyncTask[[]V] {
return Async[[]V](func() []V {
count := len(fs)
tasks := make([]*AsyncTask[V], count)
values := make([]V, count)
for i, f := range fs {
tasks[i] = Async[V](f)()
}
for i, t := range tasks {
value, err := Await[V](t)
values[i] = value
if err != nil {
panic(err)
}
}
return values
})()
}
func Race[V any](fs []func() V) *AsyncTask[V] {
return Async[V](func() V {
count := len(fs)
valueCh := make(chan V, count)
errCh := make(chan any, count)
for i := range fs {
go func(i int) {
var value V
f := fs[i]
defer func() {
if e := recover(); e == nil {
valueCh <- value
} else {
errCh <- e
}
}()
value = f()
}(i)
}
select {
case value := <-valueCh:
return value
case err := <-errCh:
panic(err)
}
})()
}