async

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

Fillmore Labs Async

Go Reference Build status GitHub Workflow Test Coverage Maintainability Go Report Card License FOSSA Status

The async package provides interfaces and utilities for writing asynchronous code in Go.

Motivation

...

Usage

Assuming you have a synchronous function func getMyIP(ctx context.Context) (string, error) returning your external IP address (see GetMyIP for an example).

Now you can do

package main

import (
	"context"
	"log/slog"
	"time"

	"fillmore-labs.com/async"
)

func main() {
	const timeout = 2 * time.Second

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	future := async.NewAsync(func() (string, error) { return getMyIP(ctx) })

	// other queries

	if ip, err := future.Await(ctx); err == nil {
		slog.Info("Found IP", "ip", ip)
	} else {
		slog.Error("Failed to fetch IP", "error", err)
	}
}

decoupling query construction from result processing.

GetMyIP

Sample code to retrieve your IP address:

package main

import (
	"context"
	"encoding/json"
	"net/http"
)

const serverURL = "https://httpbin.org/ip"

func getMyIP(ctx context.Context) (string, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, serverURL, nil)
	if err != nil {
		return "", err
	}
	req.Header.Set("Accept", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer func() { _ = resp.Body.Close() }()

	ipResponse := struct {
		Origin string `json:"origin"`
	}{}
	err = json.NewDecoder(resp.Body).Decode(&ipResponse)

	return ipResponse.Origin, err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotReady = errors.New("future not ready")

ErrNotReady is returned when a future is not complete.

Functions

This section is empty.

Types

type Future

type Future[R any] Promise[R]

Future represents a read-only view of the result of an asynchronous operation.

Construct a future either using NewAsync or from a Promise with Promise.Future.

func DoAsync

func DoAsync[R any](g Group, fn func() (R, error)) *Future[R]

DoAsync schedules an asynchronous operation on the Group and returns a Future to retrieve the eventual result.

func NewAsync

func NewAsync[R any](fn func() (R, error)) *Future[R]

NewAsync runs fn asynchronously, immediately returning a Future that can be used to retrieve the eventual result. This allows separating computation from evaluating the result.

func (*Future[R]) Await

func (f *Future[R]) Await(ctx context.Context) (R, error)

Await returns the cached result or blocks until a result is available or the context is canceled.

func (*Future[_]) Done

func (f *Future[_]) Done() <-chan struct{}

Done returns a channel that is closed when the future is complete. It enables the use of future values in select statements.

func (*Future[R]) String

func (f *Future[R]) String() string

func (*Future[R]) Try

func (f *Future[R]) Try() (R, error)

Try returns the cached result when ready, ErrNotReady otherwise.

type Group

type Group interface {
	Go(fn func() error)
}

A Group is a collection of asynchronous operations working on the same task.

type Promise

type Promise[R any] struct {
	// contains filtered or unexported fields
}

Promise defines the common operations for resolving a Future to its final value.

An empty value is valid and must not be copied after creation. One of the resolving operations may be called once from any goroutine, all subsequent calls will panic.

func (*Promise[R]) Do

func (p *Promise[R]) Do(fn func() (R, error))

Do runs fn synchronously, fulfilling the promise once it completes.

func (*Promise[R]) Future

func (p *Promise[R]) Future() *Future[R]

Future returns a Future for this promise.

func (*Promise[R]) Reject

func (p *Promise[R]) Reject(err error)

Reject breaks the promise with an error.

func (*Promise[R]) Resolve

func (p *Promise[R]) Resolve(value R)

Resolve resolves the promise with a value.

func (*Promise[R]) String

func (p *Promise[R]) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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