-
Notifications
You must be signed in to change notification settings - Fork 0
/
keeper.go
46 lines (40 loc) · 879 Bytes
/
keeper.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
package keeper
import (
"context"
"errors"
"time"
)
var FailedGetChannel = errors.New("failed to get Channel")
type result struct {
value interface{}
err error
}
// ExecWithContext wait result of f() until context canceled
func ExecWithContext(ctx context.Context, f func() (interface{}, error)) (interface{}, error) {
resultCh := make(chan result)
go func() {
defer close(resultCh)
resultCh <- func() result {
i, e := f()
return result{value: i, err: e}
}()
}()
return waitResult(ctx, resultCh)
}
// wait channel result until context done
func waitResult(ctx context.Context, ch chan result) (interface{}, error) {
var i result
for {
select {
case <-ctx.Done():
return i.value, ctx.Err()
case i, ok := <-ch:
if !ok {
return nil, FailedGetChannel
}
return i.value, i.err
default:
}
time.Sleep(1 * time.Millisecond)
}
}