async

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2023 License: MIT Imports: 6 Imported by: 0

README

Async

test Go Reference

Run async code with safe!

Example

package main

import (
	"context"
	"fmt"

	"github.com/WinPooh32/async"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	fn := func(ch chan<- async.Option[string]) error {
		err := async.TrySend(ctx, ch, "Hello Async!")
		if err != nil {
			return err
		}

		return nil
	}

	ch := async.Go(ctx, fn)

	value, err := async.Await(ctx, ch)
	if err != nil {
		panic(err)
	}

	fmt.Println(value)
}

Look for more examples at async_test.go

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrChannelClosed = errors.New("channel is closed")

Functions

func Await

func Await[T any](ctx context.Context, ch <-chan Option[T]) (value T, err error)

Await reads channel ch and unwraps option to value and error. Can be interrupted by closed context.

func Go

func Go[T any](ctx context.Context, f Func[T], capacity ...int) <-chan Option[T]

Go safely runs function f at a new goroutine. The ch channel will be closed automatically after f returns. If panic occurs inside of f it will be recovered and error will be written to the ch channel. If capacity is defined or greater than zero, buffered channel will be created.

func Group

func Group[T any](ctx context.Context, g func(i int) Func[T], n int, capacity ...int) <-chan Option[T]

Group runs g(i) functions in parallel, their output falls into one channel. n is a count of passed functions. i is ranged from 0 to n-1.

func TrySend

func TrySend[T any](ctx context.Context, ch chan<- Option[T], value T) (err error)

TrySend sends value to the ch channel, blocked until context closed or value passed to the channel.

func TrySendError

func TrySendError[T any](ctx context.Context, ch chan<- Option[T], err error) (_ error)

TrySendError sends err to the ch channel, blocked until context closed or value passed to the channel.

func With

With returns the new context containing optional values from opt funcs and context cancel func.

Types

type Func

type Func[T any] func(chan<- Option[T]) error

Func is a channel writer callback.

type OptFunc

type OptFunc func(ctx context.Context) context.Context

func Wait

func Wait() OptFunc

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a wrapped pair of value and error.

func MakeErr

func MakeErr[T any](err error) Option[T]

MakeValue wraps error.

func MakeValue

func MakeValue[T any](v T) Option[T]

MakeValue wraps value.

func (Option[T]) Err

func (opt Option[T]) Err() error

Value unwraps opt's error.

func (Option[T]) Value

func (opt Option[T]) Value() T

Value unwraps opt's value.

Jump to

Keyboard shortcuts

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