async

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2020 License: BSD-3-Clause Imports: 5 Imported by: 2

README

Async

Build Status codecov Go Report Card GoDoc

Provides a safe way to execute functions asynchronously, recovering them in case of panic. It also provides an error stack aiming to facilitate fail causes discovery, and a simple way to control execution flow without WaitGroup.

Usage

var (
    user   User
    songs  []Songs
    photos []Photos
)

err := async.Run(ctx,
    func(ctx context.Context) error {
        user, err = user.Get(ctx, id)
        return err
    },
    func(ctx context.Context) error {
        songs, err = song.GetByUserID(ctx, id)
        return err
    },
    func(ctx context.Context) error {
        photos, err = photo.GetByUserID(ctx, id)
        return err
    },
)

if err != nil {
    log.Error(err)
}

You can also limit the number of asynchronous tasks

runner := async.NewRunner(tasks...).WithLimit(3)
if err := runner.Run(ctx); err != nil { 
    log.Error(e)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(parent context.Context, tasks ...Task) error

Run provides a safe way to execute Task functions asynchronously, recovering if they panic and provides all error stack aiming to facilitate fail causes discovery

Types

type Runner

type Runner struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewRunner

func NewRunner(tasks ...Task) *Runner

NewRunner creates a new task manager to control async functions.

func (*Runner) AllErrors

func (r *Runner) AllErrors() []error

AllErrors returns all errors reported by functions

func (*Runner) Run

func (r *Runner) Run(parentCtx context.Context) error

Run starts the task manager and returns the first error or nil if succeed

func (*Runner) WaitErrors

func (r *Runner) WaitErrors() *Runner

WaitErrors tells the runner to wait for the response from all functions instead of cancelling them all when the first error occurs.

func (*Runner) WithLimit

func (r *Runner) WithLimit(limit int) *Runner

WithLimit defines a limit for concurrent tasks execution

type Task

type Task func(context.Context) error

Task ...

Jump to

Keyboard shortcuts

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