-
Notifications
You must be signed in to change notification settings - Fork 3
/
future.go
60 lines (52 loc) · 970 Bytes
/
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
package sqlz
import "time"
type Values []interface{}
func (xs Values) Error() error {
if len(xs) > 0 {
if e, ok := xs[len(xs)-1].(error); ok {
return e
}
}
return nil
}
func (xs Values) Nth(i int) interface{} {
if i < 0 {
i += len(xs)
}
if i < 0 || i >= len(xs) {
return nil
}
return xs[i]
}
func Pack(xs ...interface{}) Values { return xs }
type Future struct {
result Values
panic interface{}
done chan struct{}
}
func (f *Future) Get(timeout time.Duration) (Values, interface{}, bool) {
if timeout >= 0 {
select {
case <-time.After(timeout):
return nil, nil, false
case <-f.done:
return f.result, f.panic, true
}
} else {
<-f.done
return f.result, f.panic, true
}
}
func AsyncCall(f func() Values) Future {
future := Future{done: make(chan struct{})}
go func() {
defer func() {
if r := recover(); r != nil {
future.panic = r
}
close(future.done)
}()
future.result = f()
}()
return future
}