-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (69 loc) · 1.7 KB
/
main.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 main
import (
"time"
"errors"
"fmt"
)
func main() {
po := new(PurchaseOrder)
po.Value = 30.85
SavePO(po, false).Then(func (obj interface{}) error {
po := obj.(*PurchaseOrder)
fmt.Printf("Purchase Number Saved With iD: %d\n", po.Number)
time.Sleep(1 * time.Second)
return nil
}, func (err error) {
fmt.Printf("Purchase Number Failed With Error: " + err.Error() + "\n")
}).Then(func (obj interface{}) error {
fmt.Printf("Second Promise Success")
return nil
}, func (err error) {
fmt.Printf("Second Promise Failed: " + err.Error() + "\n")
})
fmt.Scanln()
}
type PurchaseOrder struct{
Number int
Value float64
}
func SavePO(po *PurchaseOrder, shouldFail bool) *Promise{
result := new(Promise)
result.successChannel = make(chan interface{}, 1)
result.failureChannel = make(chan error, 1)
go func() {
if shouldFail {
result.failureChannel <- errors.New("Failed To Save Purchase Order")
}else{
po.Number = 1234
result.successChannel <- po
}
}()
return result
}
type Promise struct {
successChannel chan interface{}
failureChannel chan error
}
func (this *Promise) Then(success func(interface{}) error, failure func(error)) *Promise {
result := new(Promise)
result.successChannel = make(chan interface{}, 1)
result.failureChannel = make(chan error, 1)
timeout := time.After(1 * time.Second)
go func() {
select{
case obj := <- this.successChannel:
newErr := success(obj)
if newErr == nil {
result.successChannel <- obj
}else{
result.failureChannel <- newErr
}
case err := <- this.failureChannel:
failure(err)
result.failureChannel <- err
case <- timeout:
failure(errors.New("Promise Timed Out"))
}
}()
return result
}