-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuture.go
87 lines (77 loc) · 1.61 KB
/
future.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
package bun
type PromiseHandler func(res any) any
type Promise struct {
parent *Promise
current PromiseHandler
then *Promise
exceptionally *Promise
done chan bool
}
func NewPromise(fn PromiseHandler) *Promise {
return &Promise{
parent: nil,
current: fn,
then: nil,
exceptionally: nil,
done: make(chan bool),
}
}
func (promise *Promise) Then(fn PromiseHandler) *Promise {
promise.then = &Promise{
parent: promise,
current: fn,
then: nil,
exceptionally: nil,
done: nil,
}
return promise.then
}
func (promise *Promise) Exceptionally(fn PromiseHandler) *Promise {
promise.exceptionally = &Promise{
parent: promise,
current: fn,
then: nil,
exceptionally: nil,
}
return promise.exceptionally
}
func (promise *Promise) Run() {
if promise.parent != nil {
promise.parent.Run()
return
}
promise.run(nil, promise.done)
}
func (promise *Promise) Await() {
if promise.parent != nil {
promise.parent.Await()
return
}
promise.Run()
select {
case <-promise.done:
return
}
}
func (promise *Promise) run(res any, done chan bool) {
go func() {
Try(func() {
result := promise.current(res)
if promise.then != nil {
promise.then.run(result, done)
return
}
if promise.exceptionally != nil && promise.exceptionally.then != nil {
promise.exceptionally.then.run(result, done)
return
}
done <- true
}).Catch(func(err any) {
if promise.exceptionally != nil {
promise.exceptionally.run(err, done)
return
}
done <- true
}).Run()
}()
}