-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdepend_test.go
98 lines (76 loc) · 2.21 KB
/
depend_test.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
88
89
90
91
92
93
94
95
96
97
98
package taskset_test
import (
"context"
"errors"
"fmt"
"time"
"github.com/bennydictor/taskset"
)
func ExampleDepend_ErrGroup() {
ctx := context.Background()
taskSet := taskset.NewTaskSet()
taskA := taskSet.New(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
return nil, errors.New("fail")
})
taskB := taskSet.New(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
time.Sleep(2 * time.Second)
return 2, nil
})
taskC := taskSet.New(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
if errTask := depend.ErrGroup(ctx, taskA, taskB); errTask != nil {
return nil, depend(ctx, errTask).Err
}
a := depend(ctx, taskA).Value.(int)
b := depend(ctx, taskB).Value.(int)
return a + b, nil
})
start := time.Now()
taskSet.Start(ctx)
cResult := taskSet.Result(ctx, taskC)
totalTime := time.Since(start)
fmt.Printf("total time: %.0fs\n", totalTime.Seconds())
if cResult.Err != nil {
fmt.Println("C failed:", cResult.Err.Error())
} else {
fmt.Println("C result:", cResult.Value.(int))
}
// Output:
// total time: 0s
// C failed: fail
}
func ExampleDepend_SyncGroup() {
ctx := context.Background()
taskSet := taskset.NewTaskSet()
taskA := taskSet.NewLazy(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
time.Sleep(2 * time.Second)
return nil, errors.New("fail")
})
taskB := taskSet.NewLazy(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
time.Sleep(2 * time.Second)
return 2, nil
})
taskC := taskSet.New(func(ctx context.Context, depend taskset.Depend) (interface{}, error) {
depend.SyncGroup(ctx, taskA, taskB)
var a, b int
if err := depend(ctx, taskA).Err; err == nil {
a = depend(ctx, taskA).Value.(int)
}
if err := depend(ctx, taskB).Err; err == nil {
b = depend(ctx, taskB).Value.(int)
}
return a + b, nil
})
start := time.Now()
taskSet.Start(ctx)
cResult := taskSet.Result(ctx, taskC)
totalTime := time.Since(start)
fmt.Printf("total time: %.0fs\n", totalTime.Seconds())
if cResult.Err != nil {
fmt.Println("C failed:", cResult.Err.Error())
} else {
fmt.Println("C result:", cResult.Value.(int))
}
// Output:
// total time: 2s
// C result: 2
}