Skip to content

ghosind/go-async

Repository files navigation

go-async

test Go Report Card codecov Version Badge License Badge Go Reference

English | 简体中文

It's a powerful asynchronous utility library inspired by JavaScript Promise Object and Node.js async package.

Installation and Requirement

Run the following command to install this library, and Go 1.18 and later versions required.

go get -u github.com/ghosind/go-async

And then, import the library into your own code.

import "github.com/ghosind/go-async"

This library is not stable yet, anything may change in the later versions.

Getting Started

For the following example, it runs the functions concurrently and returns the return values until all functions have been completed.

out, err := async.All(func (ctx context.Context) (int, error) {
  return 0, nil
}, func () (string, error)) {
  time.Sleep(100 * time.Millisecond)
  return "hello", nil
})
// out: [][]any{{0, <nil>}, {"hello", <nil>}}
// err: <nil>

There are over 10 asynchronous control flow functions available, please visit Go Reference to see the documentation and examples.

The function to run

The most of utility functions of this library accept any type of function to run, you can set the parameters and the return values as any type and any number of return values that you want. However, for best practice, we recommend you to set the first parameter as context.Context to receive the signals and make the type of the last return value as an error to let the utilities know whether an error happened or not.

Customize context

For all functions, you can use the XXXWithContext function (like AllWithContext, RaceWithContext, ...) to set the context by yourself.

Available Utility Functions

License

The library published under MIT License, please see license file for more details.