async

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2022 License: MIT Imports: 2 Imported by: 0

README

async go fork

Uses golang.org/x/sync/errgroup internally. API is not changed.

import (
    "context"
    "github.com/barklan/async"
)

type MyData struct {/* ... */}

func AsyncFetchData(ctx context.Context, dataID int64) async.Promise[MyData] {
    return async.NewPromise(func() (MyData, error) {
        /* ... */
        return myDataFromRemoteServer, nil
    })
}

func DealWithData(ctx context.Context) {
    myDataPromise := AsyncFetchData(ctx, 451)
    // do other stuff while operation is not settled
    // once your ready to wait for data:
    myData, err := myDataPromise.Await(ctx)
    if err != nil {/* ... */}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[T any](ctx context.Context, promises []Promise[T]) ([]T, error)

All takes a slice of promises and will await the result of all of the specified promises. If any promise should return an error, the whole result slice is nil.

Types

type Promise

type Promise[T any] interface {
	// Settled indicates if a call to Await will cause a blocking behavior, or
	// if the result will be immediately returned.
	Settled() bool

	// Await will cause the calling code to block and wait for the promise to
	// settle. Await MUST be able to be called by multiple goroutines and safely
	// deliver the same value/error to all waiting goroutines. Successive calls
	// to Await should continue to respond with the result even once the promise
	// is settled.
	Await(context.Context) (T, error)
}

Promise is an abstract representation of a value that might eventually be delivered.

func NewPromise

func NewPromise[T any](fn func() (T, error)) Promise[T]

NewPromise wraps a function in a goroutine that will make the result of that function deliver its result to the holder of the promise.

func Reject

func Reject[T any](err error) Promise[T]

Reject wraps an error in a promise that will always be immediately settled and return an error.

func Resolve

func Resolve[T any](v T) Promise[T]

Resolve wraps a value in a promise that will always be immediately settled and return the provided value.

Jump to

Keyboard shortcuts

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