-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
76 lines (65 loc) · 1.34 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
package std
import (
"context"
"github.com/pkg/errors"
"sync/atomic"
)
var ErrFutureTimeout = errors.New("future wait timeout")
type Future interface {
Wait(ctx context.Context) error
WaitData(ctx context.Context) (interface{}, error)
}
type Promise interface {
Future
Done(err error)
DoneData(err error, data interface{})
GetFuture() Future
}
type promise struct {
msk int32 // atomic op
c chan int // 同步chan
data interface{} // 存放交换的数据
err error
}
func NewPromise() Promise {
return &promise{
msk: 0,
c: make(chan int),
}
}
// get future
func (this *promise) GetFuture() Future {
return this
}
func (this *promise) Wait(ctx context.Context) error {
_, err := this.WaitData(ctx)
return err
}
func (this *promise) WaitData(ctx context.Context) (interface{}, error) {
select {
case <-this.c:
return this.data, this.err
default:
{
select {
case <-ctx.Done():
return nil, ErrFutureTimeout
case <-this.c:
}
return this.data, this.err
}
}
}
//完成等待
func (this *promise) Done(err error) {
this.DoneData(err, nil)
}
//完成等待,同时传递数据.只允许调用一次,多次调用,只生效一次
func (this *promise) DoneData(err error, data interface{}) {
if atomic.CompareAndSwapInt32(&this.msk, 0, 1) {
this.err = err
this.data = data
close(this.c)
return
}
}