@@ -44,26 +44,7 @@ func all(parent context.Context, funcs ...AsyncFn) (int, error) {
4444 defer close (ch )
4545
4646 for i := 0 ; i < len (funcs ); i ++ {
47- fn := funcs [i ]
48- n := i
49- go func () {
50- childCtx , childCanFunc := context .WithCancel (ctx )
51- defer childCanFunc ()
52-
53- err := utils .Try (func () error {
54- return fn (childCtx )
55- })
56-
57- select {
58- case <- ctx .Done ():
59- return
60- default :
61- ch <- executeResult {
62- Error : err ,
63- Index : n ,
64- }
65- }
66- }()
47+ go runTaskInAll (ctx , i , funcs [i ], ch )
6748 }
6849
6950 finished := 0
@@ -82,6 +63,26 @@ func all(parent context.Context, funcs ...AsyncFn) (int, error) {
8263 return - 1 , nil
8364}
8465
66+ // runTaskInAll runs the specified function for All / AllWithContext.
67+ func runTaskInAll (ctx context.Context , n int , fn AsyncFn , ch chan <- executeResult ) {
68+ childCtx , childCanFunc := context .WithCancel (ctx )
69+ defer childCanFunc ()
70+
71+ err := utils .Try (func () error {
72+ return fn (childCtx )
73+ })
74+
75+ select {
76+ case <- ctx .Done ():
77+ return
78+ default :
79+ ch <- executeResult {
80+ Error : err ,
81+ Index : n ,
82+ }
83+ }
84+ }
85+
8586// AllCompleted executes the functions asynchronously until all functions have been finished. It
8687// will return an error slice that is ordered by the functions order, and a boolean value to
8788// indicate whether any functions return an error or panic.
@@ -118,9 +119,9 @@ func allCompleted(
118119 wg .Add (len (funcs ))
119120
120121 for i := 0 ; i < len (funcs ); i ++ {
121- n := i
122- fn := funcs [n ]
123- go func () {
122+ go func ( n int ) {
123+ fn := funcs [n ]
124+
124125 childCtx , childCanFunc := context .WithCancel (parent )
125126 defer childCanFunc ()
126127 defer wg .Done ()
@@ -132,7 +133,7 @@ func allCompleted(
132133 hasError = true
133134 errs [n ] = err
134135 }
135- }()
136+ }(i )
136137 }
137138
138139 wg .Wait ()
0 commit comments