-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
47 lines (39 loc) · 822 Bytes
/
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
package wfcache
import (
"context"
)
type Future interface {
Await() (interface{}, error)
AwaitWithContext(context.Context) (interface{}, error)
}
type promise struct {
await func(ctx context.Context) (interface{}, error)
}
func (f promise) Await() (interface{}, error) {
return f.await(context.Background())
}
func (f promise) AwaitWithContext(ctx context.Context) (interface{}, error) {
return f.await(ctx)
}
func Promise(f func() (interface{}, error)) Future {
var val interface{}
var err error
c := make(chan struct{})
go func() {
defer close(c)
val, err = f()
}()
return promise{
await: func(ctx context.Context) (interface{}, error) {
select {
case <-c:
if err != nil {
return nil, err
}
return val, nil
case <-ctx.Done():
return nil, ctx.Err()
}
},
}
}