-
Notifications
You must be signed in to change notification settings - Fork 1
/
deferred.go
54 lines (43 loc) · 1.04 KB
/
deferred.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
package promises
import "sync"
type Deferred struct {
stateOnce *sync.Once
fulfilled chan PromiseResult
rejected chan PromiseResult
}
func (promise *Deferred) onFulfilled() chan PromiseResult {
return promise.fulfilled
}
func (promise *Deferred) onRejected() chan PromiseResult {
return promise.rejected
}
func (promise *Deferred) Then(next func(PromiseResult) Promise) Promise {
return then(promise, next)
}
func (promise *Deferred) Fail(next func(PromiseResult) Promise) Promise {
return fail(promise, next)
}
func (promise *Deferred) Resolve(value PromiseResult) {
promise.stateOnce.Do(func() {
promise.fulfilled <- value
})
}
func (promise *Deferred) Reject(reason PromiseResult) {
promise.stateOnce.Do(func() {
promise.rejected <- reason
})
}
func (promise *Deferred) Done() {
done(promise)
}
func newDeferred() *Deferred {
promise := &Deferred{
stateOnce: new(sync.Once),
fulfilled: make(chan PromiseResult, 1),
rejected: make(chan PromiseResult, 1),
}
return promise
}
func Defer() *Deferred {
return newDeferred()
}