Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async/await #195

Merged
merged 1 commit into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions async/async.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package async

import "context"

// Future mimics the async/await paradigm
type Future[T any] interface {
Await() (T, error)
}

type future[T any] struct {
await func(ctx context.Context) (T, error)
}

func (f future[T]) Await() (T, error) {
return f.await(context.Background())
}

func Exec[T any](f func() (T, error)) Future[T] {
var (
result T
err error
)
c := make(chan struct{})
go func() {
defer close(c)

result, err = f()
}()
return future[T]{
await: func(ctx context.Context) (T, error) {
select {
case <-ctx.Done():
return result, ctx.Err()
case <-c:
return result, err
}
},
}
}
24 changes: 24 additions & 0 deletions async/async_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package async

import (
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestAsync(t *testing.T) {
// Async
do := Exec(func() (bool, error) {
time.Sleep(2 * time.Second)
return true, nil
})

// do some other stuff
time.Sleep(time.Second)

// Await
ok, err := do.Await()
require.Nil(t, err)
require.True(t, ok)
}
Loading