|
1 | 1 | # go-async
|
2 |
| -Asynchronous workflow functions for Golang. |
| 2 | + |
| 3 | + |
| 4 | +[](https://goreportcard.com/report/github.com/ghosind/go-async) |
| 5 | +[](https://codecov.io/gh/ghosind/go-async) |
| 6 | + |
| 7 | + |
| 8 | +[](https://pkg.go.dev/github.com/ghosind/go-async) |
| 9 | + |
| 10 | +A tool collection that provided asynchronous workflow control utilities, inspired by `Promise` in the Javascript. |
| 11 | + |
| 12 | +## Installation |
| 13 | + |
| 14 | +```sh |
| 15 | +go get -u github.com/ghosind/go-async |
| 16 | +``` |
| 17 | + |
| 18 | +## Getting Started |
| 19 | + |
| 20 | +We provided the `All` function to execute all the functions asynchronously. It'll return `-1` and a nil error if all functions are completed and no error return or panic. If some function returns an error or panic, it'll immediately return the index of the function and the error and send the cancel signal to all other functions. |
| 21 | + |
| 22 | +```go |
| 23 | +index, err := async.All(func (ctx context.Context) error) { |
| 24 | + return nil |
| 25 | +}, func (ctx context.Context) error) { |
| 26 | + return nil |
| 27 | +}/*, ...*/) |
| 28 | +// index: -1 |
| 29 | +// err: <nil> |
| 30 | + |
| 31 | +index, err := async.All(func (ctx context.Context) error) { |
| 32 | + return nil |
| 33 | +}, func (ctx context.Context) error) { |
| 34 | + return errors.New("some error") |
| 35 | +}/*, ...*/) |
| 36 | +// index: 1 |
| 37 | +// err: Some error |
| 38 | +``` |
| 39 | + |
| 40 | +If you do not want to terminate the execution of other functions if some function returns an error or panic, you can try the `AllCompleted` function. The `AllCompleted` function will return until all functions are finished or panic. It'll return a list of the function return values (error), and a boolean value to indicate any functions return error or panic. |
| 41 | + |
| 42 | +```go |
| 43 | +errors, ok := async.All(func (ctx context.Context) error) { |
| 44 | + return nil |
| 45 | +}, func (ctx context.Context) error) { |
| 46 | + return errors.New("some error") |
| 47 | +}/*, ...*/) |
| 48 | +// errors: [<nil>, some error] |
| 49 | +// ok: false |
| 50 | +``` |
| 51 | + |
| 52 | +We also provided the `Race` function, it will return when a function returns or panics, and does not terminate other functions. |
| 53 | + |
| 54 | +```go |
| 55 | +index, err := async.Race(func (ctx context.Context) error { |
| 56 | + request.Get("https://example.com") |
| 57 | + return nil |
| 58 | +}, func (ctx context.Context) error { |
| 59 | + time.Sleep(time.Second) |
| 60 | + return nil |
| 61 | +}) |
| 62 | +// index = 0 if the request is finished within one second. |
| 63 | +// index = 1 if the request is finished after one second. |
| 64 | +``` |
0 commit comments