Skip to content

Commit

Permalink
ActionToFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
haitch committed Oct 26, 2022
1 parent 8d4616f commit a0063e7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions task.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import (
"time"
)

// ActionToFunc convert a Action to Func (C# term), to satisfy the AsyncFunc interface.
// Action is function that runs without return anything
// Func is function that runs and return something
func ActionToFunc(action func(context.Context) error) func(context.Context) (*interface{}, error) {
return func(ctx context.Context) (*interface{}, error) {
return nil, action(ctx)
}
}

// AsyncFunc is a function interface this asyncTask accepts.
type AsyncFunc[T any] func(context.Context) (*T, error)

Expand Down
14 changes: 14 additions & 0 deletions task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,20 @@ func TestCompletedGenericTask(t *testing.T) {
assert.Equal(t, *resultGet, result)
}

func TestActionToFunc(t *testing.T) {
t.Parallel()

action := func(ctx context.Context) error {
return nil
}

ctx := context.Background()
task := asynctask.Start(ctx, asynctask.ActionToFunc(action))
result, err := task.Result(ctx)
assert.NoError(t, err)
assert.Nil(t, result)
}

func TestCrazyCaseGeneric(t *testing.T) {
t.Parallel()
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
Expand Down

0 comments on commit a0063e7

Please sign in to comment.