-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
59 lines (48 loc) · 1.09 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
package promise
import (
"sync/atomic"
)
type Promise[T any] struct {
success Pending[T]
fail Pending[error]
final PendingNoValue
state int32
}
type State int32
const (
StatePending State = iota
StateResolved
StateError
)
func NewPromise[T any]() *Promise[T] {
return &Promise[T]{}
}
func (prom *Promise[T]) Then(f func(v T)) *Promise[T] {
prom.success.Then(f)
return prom
}
func (prom *Promise[T]) Catch(f func(err error)) *Promise[T] {
prom.fail.Then(f)
return prom
}
func (prom *Promise[T]) Finally(f func()) *Promise[T] {
prom.final.Then(f)
return prom
}
func (prom *Promise[T]) Resolve(v T) {
// make sure this runs once
if atomic.CompareAndSwapInt32(&prom.state, int32(StatePending), int32(StateResolved)) {
defer prom.final.Resolve()
prom.success.Resolve(v)
}
}
func (prom *Promise[T]) Error(err error) {
// make sure this runs once
if atomic.CompareAndSwapInt32(&prom.state, int32(StatePending), int32(StateError)) {
defer prom.final.Resolve()
prom.fail.Resolve(err)
}
}
func (prom *Promise[T]) State() State {
return State(atomic.LoadInt32(&prom.state))
}