async

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2023 License: MIT Imports: 3 Imported by: 0

README

Golang Async/Await

Go Report Card PkgGoDev

An implementation that makes managing async tasks easier

Installation

go get -u github.com/JingIsCoding/async

Usage

From v1.0.1 using Golang generics to enforce typed result
Resolves the future with string type
future := Async(func(res Resolve[string], rej Reject[error]) {
  // do something asynchronously 
  res("yes")
})
result := future.Await()
// do something with the result
fmt.Println(result.Value())
Resolves the future with custom type
type User struct {
  Name string
}
// somewhere in the code
result := Async(func(res Resolve[User], rej Reject[error]) {
  res(User{Name:":"some one"})
}).Await()
// do something with the result
fmt.Println(result.Value().Name)
Reject the future
result := Async(func(res Resolve[interface{}], rej Reject[error]) {
	rej(errors.New("something is wrong"))
}).Await()
fmt.Printf("%t", result.IsOK())
fmt.Printf("%e", result.Error())
// do something with the result that has error
With context
ctx, _ := context.WithTimeout(context.Background(), time.Duration(1*time.Second))
future := Async(func(res Resolve[string], rej Reject[error]) {
  time.Sleep(3 * time.Second)
  res("should not see this")
}, ctx)
result := future.Await()
// Failed to resolve because the context timeouts

License

Distributed under MIT License. See LICENSE file for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Func

type Func[T any, E error] func(Resolve[T], Reject[E])

type Future

type Future[T any, E error] interface {
	Await() Result[T, E]
}

func Async

func Async[T any, E error](ctx context.Context, fun Func[T, E]) Future[T, E]

type Futures added in v1.0.3

type Futures[T any, E error] interface {
	Await() Results[T, E]
}

func AsyncAll added in v1.0.3

func AsyncAll[T any, E error](ctx context.Context, funcs ...Func[T, E]) Futures[T, E]

type Reject

type Reject[E error] func(E)

type Resolve

type Resolve[T any] func(T)

type Result

type Result[T any, E error] struct {
	// contains filtered or unexported fields
}

func (Result[T, E]) Error

func (result Result[T, E]) Error() *E

func (Result[T, E]) IsOk added in v1.0.3

func (result Result[T, E]) IsOk() bool

func (Result[T, E]) Value

func (result Result[T, E]) Value() *T

type Results added in v1.0.3

type Results[T any, E error] []Result[T, E]

func (Results[T, E]) Error added in v1.0.3

func (results Results[T, E]) Error() []*E

func (Results[T, E]) IsOk added in v1.0.3

func (results Results[T, E]) IsOk() bool

func (Results[T, E]) Value added in v1.0.3

func (results Results[T, E]) Value() []*T

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL