forked from hoanguyenkh/promise4g
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.go
221 lines (198 loc) · 5.48 KB
/
promise.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package promise4g
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
// Promise represents a computation that will eventually be completed with a value of type T or an error.
type Promise[T any] struct {
value atomic.Value
err atomic.Value
done chan struct{}
once sync.Once
startTime time.Time
}
// New creates a new Promise with the given task
func New[T any](task func(resolve func(T), reject func(error))) *Promise[T] {
return NewWithPool(task, defaultPool)
}
// NewWithPool creates a new Promise with the given task and pool
func NewWithPool[T any](task func(resolve func(T), reject func(error)), pool Pool) *Promise[T] {
if task == nil {
panic("task must not be nil")
}
if pool == nil {
panic("pool must not be nil")
}
incrementPromisesCreated()
incrementConcurrentPromises()
p := &Promise[T]{
done: make(chan struct{}),
startTime: time.Now(),
}
pool.Go(func() {
defer p.handlePanic()
defer decrementConcurrentPromises()
task(p.resolve, p.reject)
})
return p
}
// Await waits for the Promise to be resolved or rejected
func (p *Promise[T]) Await(ctx context.Context) (T, error) {
select {
case <-ctx.Done():
var t T
return t, ctx.Err()
case <-p.done:
if err := p.err.Load(); err != nil {
var t T
return t, err.(error)
}
return p.value.Load().(T), nil
}
}
func (p *Promise[T]) resolve(value T) {
p.once.Do(func() {
p.value.Store(value)
observePromiseExecutionTime(time.Since(p.startTime).Seconds())
close(p.done)
})
}
func (p *Promise[T]) reject(err error) {
p.once.Do(func() {
p.err.Store(err)
observePromiseExecutionTime(time.Since(p.startTime).Seconds())
close(p.done)
})
}
func (p *Promise[T]) handlePanic() {
if r := recover(); r != nil {
var err error
switch v := r.(type) {
case error:
err = v
default:
err = fmt.Errorf("%v", v)
}
p.reject(err)
}
}
// All waits for all promises to be resolved
func All[T any](ctx context.Context, promises ...*Promise[T]) *Promise[[]T] {
return AllWithPool(ctx, defaultPool, promises...)
}
// AllWithPool waits for all promises to be resolved using the given pool
func AllWithPool[T any](ctx context.Context, pool Pool, promises ...*Promise[T]) *Promise[[]T] {
if len(promises) == 0 {
panic("missing promises")
}
return NewWithPool(func(resolve func([]T), reject func(error)) {
results := make([]T, len(promises))
var wg sync.WaitGroup
wg.Add(len(promises))
for i, p := range promises {
i, p := i, p
pool.Go(func() {
defer wg.Done()
result, err := p.Await(ctx)
if err != nil {
reject(err)
return
}
results[i] = result
})
}
wg.Wait()
resolve(results)
}, pool)
}
// Race returns a promise that resolves or rejects as soon as one of the promises resolves or rejects
func Race[T any](ctx context.Context, promises ...*Promise[T]) *Promise[T] {
return NewWithPool(func(resolve func(T), reject func(error)) {
for _, p := range promises {
p := p // Create a new variable to avoid closure issues
defaultPool.Go(func() {
result, err := p.Await(ctx)
if err != nil {
reject(err)
} else {
resolve(result)
}
})
}
}, defaultPool)
}
// Then chains a new Promise to the current one
func Then[A, B any](p *Promise[A], ctx context.Context, resolve func(A) (B, error)) *Promise[B] {
return ThenWithPool(p, ctx, resolve, defaultPool)
}
// ThenWithPool chains a new Promise to the current one using the given pool
func ThenWithPool[A, B any](p *Promise[A], ctx context.Context, resolve func(A) (B, error), pool Pool) *Promise[B] {
return NewWithPool(func(resolveB func(B), reject func(error)) {
result, err := p.Await(ctx)
if err != nil {
reject(err)
return
}
resultB, err := resolve(result)
if err != nil {
reject(err)
return
}
resolveB(resultB)
}, pool)
}
// Catch handles errors in the Promise chain
func Catch[T any](p *Promise[T], ctx context.Context, reject func(error) error) *Promise[T] {
return CatchWithPool(p, ctx, reject, defaultPool)
}
// CatchWithPool handles errors in the Promise chain using the given pool
func CatchWithPool[T any](p *Promise[T], ctx context.Context, reject func(error) error, pool Pool) *Promise[T] {
return NewWithPool(func(resolve func(T), internalReject func(error)) {
result, err := p.Await(ctx)
if err != nil {
internalReject(reject(err))
} else {
resolve(result)
}
}, pool)
}
// Finally executes a function regardless of whether the promise is fulfilled or rejected
func Finally[T any](p *Promise[T], ctx context.Context, fn func()) *Promise[T] {
return NewWithPool(func(resolve func(T), reject func(error)) {
result, err := p.Await(ctx)
fn()
if err != nil {
reject(err)
} else {
resolve(result)
}
}, defaultPool)
}
// Timeout returns a new Promise that rejects if the original Promise doesn't resolve within the specified duration
func Timeout[T any](p *Promise[T], d time.Duration) *Promise[T] {
ctx, cancel := context.WithTimeout(context.Background(), d)
return NewWithPool(func(resolve func(T), reject func(error)) {
defer cancel()
result, err := p.Await(ctx)
if err != nil {
reject(err)
} else {
resolve(result)
}
}, defaultPool)
}
// AsyncTask creates a new Promise that executes the provided function asynchronously.
// It resolves with the function's result or rejects with an error if the function fails.
func AsyncTask[T any](fn func() (T, error)) *Promise[T] {
return New(func(resolve func(T), reject func(error)) {
resp, err := fn()
if err != nil {
reject(err)
} else {
resolve(resp)
}
})
}