Skip to content

Commit 884f779

Browse files
committed
feat: add getContext.
1 parent ddb599f commit 884f779

File tree

4 files changed

+34
-9
lines changed

4 files changed

+34
-9
lines changed

all.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,7 @@ func all(parent context.Context, funcs ...AsyncFn) (int, error) {
3535
return -1, nil
3636
}
3737

38-
if parent == nil {
39-
parent = context.Background()
40-
}
38+
parent = getContext(parent)
4139

4240
ctx, canFunc := context.WithCancel(parent)
4341
defer canFunc()
@@ -114,9 +112,7 @@ func allCompleted(
114112
return
115113
}
116114

117-
if parent == nil {
118-
parent = context.Background()
119-
}
115+
parent = getContext(parent)
120116

121117
wg := sync.WaitGroup{}
122118
wg.Add(len(funcs))

async.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,13 @@ type executeResult struct {
1515
// Index is the index of the function in the parameters list.
1616
Index int
1717
}
18+
19+
// getContext returns the specified non-nil context from the parameter, or creates and returns a
20+
// new empty context.
21+
func getContext(ctx context.Context) context.Context {
22+
if ctx != nil {
23+
return ctx
24+
}
25+
26+
return context.Background()
27+
}

async_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package async
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/ghosind/go-assert"
8+
)
9+
10+
func TestGetContext(t *testing.T) {
11+
a := assert.New(t)
12+
13+
todoCtx := context.TODO()
14+
ctx := getContext(todoCtx)
15+
a.EqualNow(ctx, todoCtx)
16+
17+
//lint:ignore SA1012 for test case only
18+
ctx = getContext(nil)
19+
a.NotNilNow(ctx)
20+
a.NotEqualNow(ctx, todoCtx)
21+
}

race.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ func race(ctx context.Context, funcs ...AsyncFn) (int, error) {
2828
return -1, nil
2929
}
3030

31-
if ctx == nil {
32-
ctx = context.Background()
33-
}
31+
ctx = getContext(ctx)
3432

3533
finished := atomic.Bool{}
3634
ch := make(chan executeResult)

0 commit comments

Comments
 (0)