-
Notifications
You must be signed in to change notification settings - Fork 0
/
fulfilled.go
98 lines (80 loc) · 2.48 KB
/
fulfilled.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
/**********************************************************\
* *
* promise/fulfilled.go *
* *
* fulfilled promise implementation for Go. *
* *
* LastModified: Sep 11, 2016 *
* Author: Ma Bingyao <[email protected]> *
* *
\**********************************************************/
package promise
import "time"
type fulfilled struct {
value interface{}
}
// Resolve creates a Promise object completed with the value.
func Resolve(value interface{}) Promise {
if promise, ok := value.(Promise); ok {
p := New()
promise.Fill(p)
return p
}
return &fulfilled{value}
}
// ToPromise convert value to a Promise object.
// If the value is already a promise, return it in place
func ToPromise(value interface{}) Promise {
if promise, ok := value.(Promise); ok {
return promise
}
return &fulfilled{value}
}
func (p *fulfilled) Then(onFulfilled OnFulfilled, onRejected ...OnRejected) Promise {
if onFulfilled == nil {
return &fulfilled{p.value}
}
next := New()
resolve(next, onFulfilled, p.value)
return next
}
func (p *fulfilled) Catch(onRejected OnRejected, test ...func(error) bool) Promise {
return &fulfilled{p.value}
}
func (p *fulfilled) Complete(onCompleted OnCompleted) Promise {
return p.Then(onCompleted)
}
func (p *fulfilled) WhenComplete(action func()) Promise {
return p.Then(func(v interface{}) interface{} {
action()
return v
})
}
func (p *fulfilled) Done(onFulfilled OnFulfilled, onRejected ...OnRejected) {
p.Then(onFulfilled).Then(nil, func(e error) { go panic(e) })
}
func (p *fulfilled) State() State {
return FULFILLED
}
func (p *fulfilled) Resolve(value interface{}) {}
func (p *fulfilled) Reject(reason error) {}
func (p *fulfilled) Fill(promise Promise) {
go promise.Resolve(p.value)
}
func (p *fulfilled) Timeout(duration time.Duration, reason ...error) Promise {
return timeout(p, duration, reason...)
}
func (p *fulfilled) Delay(duration time.Duration) Promise {
next := New()
go func() {
time.Sleep(duration)
next.Resolve(p.value)
}()
return next
}
func (p *fulfilled) Tap(onfulfilledSideEffect func(interface{})) Promise {
return tap(p, onfulfilledSideEffect)
}
func (p *fulfilled) Get() (interface{}, error) {
return p.value, nil
}