Skip to content

Commit 63ffec8

Browse files
committed
feat: implement All with Paralleler.
1 parent 3df4d8e commit 63ffec8

File tree

2 files changed

+5
-54
lines changed

2 files changed

+5
-54
lines changed

all.go

Lines changed: 4 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -50,61 +50,12 @@ func AllWithContext(ctx context.Context, funcs ...AsyncFn) ([][]any, error) {
5050
// all executes the functions asynchronously until all functions have been finished, or the context
5151
// is done (canceled or timeout).
5252
func all(parent context.Context, funcs ...AsyncFn) ([][]any, error) {
53-
if len(funcs) == 0 {
54-
return nil, nil
55-
}
56-
validateAsyncFuncs(funcs...)
57-
58-
parent = getContext(parent)
59-
60-
ctx, canFunc := context.WithCancel(parent)
61-
defer canFunc()
62-
63-
ch := make(chan executeResult, len(funcs))
64-
defer close(ch)
65-
66-
for i := 0; i < len(funcs); i++ {
67-
go runTaskInAll(ctx, i, funcs[i], ch)
68-
}
69-
70-
finished := 0
71-
out := make([][]any, len(funcs))
72-
for finished < len(funcs) {
73-
select {
74-
case <-parent.Done():
75-
return out, ErrContextCanceled
76-
case ret := <-ch:
77-
out[ret.Index] = ret.Out
78-
if ret.Error != nil {
79-
return out, &executionError{
80-
index: ret.Index,
81-
err: ret.Error,
82-
}
83-
}
84-
finished++
85-
}
86-
}
53+
paralleler := new(Paralleler).
54+
WithContext(parent)
8755

88-
return out, nil
89-
}
56+
paralleler.Add(funcs...)
9057

91-
// runTaskInAll runs the specified function for All / AllWithContext.
92-
func runTaskInAll(ctx context.Context, n int, fn AsyncFn, ch chan<- executeResult) {
93-
childCtx, childCanFunc := context.WithCancel(ctx)
94-
defer childCanFunc()
95-
96-
ret, err := invokeAsyncFn(fn, childCtx, nil)
97-
98-
select {
99-
case <-ctx.Done():
100-
return
101-
default:
102-
ch <- executeResult{
103-
Error: err,
104-
Index: n,
105-
Out: ret,
106-
}
107-
}
58+
return paralleler.Run()
10859
}
10960

11061
// AllCompleted executes the functions asynchronously until all functions have been finished. It

all_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestAllWithoutFuncs(t *testing.T) {
1616

1717
out, err := async.All()
1818
a.NilNow(err)
19-
a.NilNow(out)
19+
a.EqualNow(out, [][]any{})
2020
}
2121

2222
func TestAllSuccess(t *testing.T) {

0 commit comments

Comments
 (0)