goalbatch

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2020 License: MIT Imports: 2 Imported by: 0

README

goalbatch

goalbatch badge Go Report Card codecov license

goalbatch - A simple way to execute functions asynchronously and waits for results

Batch

Batch method returns when all of the callbacks passed or context is done, returned responses and errors are ordered according to callback order

	timeout := time.Duration(100) * time.Millisecond
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	g := goalbatch.New(ctx)
	rs, errs := g.Batch(
		func(ctx context.Context) (interface{}, error) {
			time.Sleep(5 * time.Second)
			return 1, nil
		},
		func(ctx context.Context) (interface{}, error) {
			return nil, errors.New("failed")
		},
		func(ctx context.Context) (interface{}, error) {
			return 3, nil
		},
		func(ctx context.Context) (interface{}, error) {
			return 4, nil
		},
	)

	fmt.Println(rs)
	fmt.Println(errs)
	// Output:
	// [<nil> <nil> 3 4]
	// [<nil> "failed" <nil> <nil>]

Or generate closure functions with parameters:

	newAsyncFunc := func(ctx context.Context, param1 string, param2 int) AsyncFunc {
		return func(ctx context.Context) (interface{}, error) {
			// deal with param1, param2...
			result := fmt.Sprintf("p1=%s p2=%d", param1, param2)
			return result, nil
		}
	}

	fns := make([]AsyncFunc, 2)
	fns[0] = newAsyncFunc(ctx, "foo", 1)
	fns[1] = newAsyncFunc(ctx, "bar", 2)

	g := goalbatch.New(ctx)
	rs, errs := g.Batch(fns...)

	fmt.Println(rs)
	fmt.Println(errs)
	// Output:
	// ["p1=foo p2=1" "p1=bar p2=2"]
	// [<nil> <nil>]

Documentation

Overview

Package goalbatch A simple way to execute functions asynchronously and waits for results

The idea come from github.com/vardius/gollback, but more suitable for concurrent waiting scenarios

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncFunc

type AsyncFunc func(ctx context.Context) (interface{}, error)

AsyncFunc represents asynchronous function

type Goalbatch

type Goalbatch interface {
	// Batch method returns when all of the callbacks passed or context is done,
	// returned responses and errors are ordered according to callback order
	Batch(fns ...AsyncFunc) ([]interface{}, []error)
}

Goalbatch provides set of utility methods to easily manage asynchronous functions

func New

func New(ctx context.Context) Goalbatch

New creates new goalbatch

Jump to

Keyboard shortcuts

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