-
Notifications
You must be signed in to change notification settings - Fork 2
/
promise.go
97 lines (87 loc) · 1.63 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
package go_future
import (
"fmt"
"sync/atomic"
)
var eventBus = make(chan *func() bool)
type Promise struct {
id uint64
handler bool
rev <-chan interface{}
errChan chan error
doneFlag bool
done chan struct{}
}
func (e *eventLoop) newPromise(rev <-chan interface{}, errChan chan error) *Promise {
currentP := &Promise{id: uint64(atomic.AddInt64(&e.size, 1)), rev: rev, errChan: errChan, done: make(chan struct{})}
e.sync.Lock()
e.promiseQueue = append(e.promiseQueue, currentP)
e.sync.Unlock()
return currentP
}
func (p *Promise) complete() {
close(p.done)
}
func (p *Promise) registerHandler() {
p.handler = true
}
func (p *Promise) Then(fn func(interface{})) *Promise {
p.registerHandler()
work := func() bool {
select {
default:
if p.doneFlag {
return true
}
return false
case val := <-p.rev:
go func() {
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case error:
p.errChan <- x
default:
p.errChan <- fmt.Errorf("%v", x)
}
} else {
p.doneFlag = true
p.complete()
}
}()
fn(val)
}()
return true
}
}
eventBus <- &work
return p
}
func (p *Promise) Catch(fn func(err error)) {
p.registerHandler()
work := func() bool {
select {
default:
if p.doneFlag {
return true
}
return false
case err := <-p.errChan:
p.doneFlag = true
go fn(err)
p.complete()
return true
}
}
eventBus <- &work
}
func (p *Promise) Await() (any, error) {
defer p.complete()
p.registerHandler()
select {
case err := <-p.errChan:
return nil, err
case rev := <-p.rev:
return rev, nil
}
}