Skip to content

Commit

Permalink
feat: support ctx argument in Async
Browse files Browse the repository at this point in the history
Signed-off-by: jizhuozhi <[email protected]>
  • Loading branch information
jizhuozhi committed Jan 20, 2025
1 parent fab0c88 commit af7fa04
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package future

import (
"context"
"errors"
"fmt"
"runtime/debug"
Expand All @@ -27,6 +28,22 @@ func Async[T any](f func() (T, error)) *Future[T] {
return &Future[T]{state: s}
}

func CtxAsync[T any](ctx context.Context, f func(ctx context.Context) (T, error)) *Future[T] {
s := &state[T]{}
go func() {
var val T
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%w, err=%s, stack=%s", ErrPanic, r, debug.Stack())
}
s.set(val, err)
}()
val, err = f(ctx)
}()
return &Future[T]{state: s}
}

func Lazy[T any](f func() (T, error)) *Future[T] {
s := &state[T]{}
s.state |= flagLazy
Expand Down
11 changes: 11 additions & 0 deletions api_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package future

import (
"context"
"math/rand"
"runtime"
"strconv"
Expand All @@ -21,6 +22,16 @@ func TestAsync(t *testing.T) {
assert.Equal(t, nil, err)
}

func TestCtxAsync(t *testing.T) {
ctx := context.WithValue(context.Background(), "foo", "bar")
f := CtxAsync(ctx, func(ctx context.Context) (any, error) {
return ctx.Value("foo"), nil
})
val, err := f.Get()
assert.Equal(t, "bar", val)
assert.Equal(t, nil, err)
}

func TestAsyncPanic(t *testing.T) {
f := Async(func() (int, error) {
panic("panic")
Expand Down

0 comments on commit af7fa04

Please sign in to comment.