-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpromises.go
114 lines (92 loc) · 2.03 KB
/
promises.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
package go_promise
import (
"sync"
)
type Promises []Promise
func AllSettled[V any](ps Promises) Promise {
return New(func(resolve ResolveFunc[SettledResults[V]], reject RejectFunc) {
resultChan := runRoutines[V](ps)
values := make(SettledResults[V], 0, len(ps))
for result := range resultChan {
values = append(values, result)
}
resolve(values)
})
}
func All[V any](ps Promises) Promise {
return New(func(resolve ResolveFunc[[]V], reject RejectFunc) {
resultChan := runRoutines[V](ps)
values := make([]V, 0, len(ps))
for result := range resultChan {
if result.Error != nil {
reject(result.Error)
go resultChan.empty()
return
}
values = append(values, result.Value)
}
resolve(values)
})
}
func Any[V any](ps Promises) Promise {
return New(func(resolve ResolveFunc[V], reject RejectFunc) {
resultChan := runRoutines[V](ps)
errs := make(Errors, 0, len(ps))
for result := range resultChan {
if result.Error != nil {
errs = append(errs, result.Error)
continue
}
resolve(result.Value)
go resultChan.empty()
return
}
reject(errs)
})
}
func Race[V any](ps Promises) Promise {
return New(func(resolve ResolveFunc[V], reject RejectFunc) {
resultChan := runRoutines[V](ps)
result := <-resultChan
if result.Error != nil {
reject(result.Error)
} else {
resolve(result.Value)
}
go resultChan.empty()
})
}
func runRoutines[V any](ps Promises) settledResultChanel[V] {
resultChan := make(settledResultChanel[V])
group := &sync.WaitGroup{}
group.Add(len(ps))
for _, promise := range ps {
go func(p Promise) {
value, err := p.await()
if err != nil {
resultChan <- SettledResult[V]{
Error: err,
}
group.Done()
return
}
transformed, ok := value.(V)
if !ok {
resultChan <- SettledResult[V]{
Error: InvalidTypeErr,
}
group.Done()
return
}
resultChan <- SettledResult[V]{
Value: transformed,
}
group.Done()
}(promise)
}
go func() {
group.Wait()
close(resultChan)
}()
return resultChan
}