Async is an async/await like task package for Go
- Wait/WaitAny/WaitN for
Task
andAction
context.Context
withtimeout
,cancel
support- Works with generic instead of
interface{}
see more examples on tasks, actions or go.dev
- install latest commit from
main
branch
go get github.com/yaitoo/async@main
- install latest release
go get github.com/yaitoo/async@latest
wait all tasks to completed.
t := async.New[int](func(ctx context.Context) (int, error) {
return 1, nil
}, func(ctx context.Context) (int, error) {
return 2, nil
})
result, err, taskErrs := t.Wait(context.Background())
fmt.Println(result) //[1,2] or [2,1]
fmt.Println(err) // nil
fmt.Println(taskErrs) //nil
wait any task to completed
t := async.New[int](func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 1, nil
}, func(ctx context.Context) (int, error) {
return 2, nil
})
result, err, taskErrs := t.WaitAny(context.Background())
fmt.Println(result) //2
fmt.Println(err) //nil
fmt.Println(taskErrs) //nil
wait N tasks to completed.
t := async.New[int](func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 1, nil
}, func(ctx context.Context) (int, error) {
return 2, nil
}, func(ctx context.Context) (int, error) {
return 3, nil
})
result, err, taskErrs := t.WaitN(context.Background(),2)
fmt.Println(result) //[2,3] or [3,2]
fmt.Println(err) //nil
fmt.Println(taskErrs) //nil
cancel all tasks if it is timeout.
t := async.New[int](func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 1, nil
}, func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 2, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
result, err, tasks := t.WaitAny(ctx)
//result, err, tasks := t.Wait(ctx)
fmt.Println(result) //nil
fmt.Println(err) // context.DeadlineExceeded
fmt.Println(taskErrs) //nil
manually cancel all tasks.
t := async.New[int](func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 1, nil
}, func(ctx context.Context) (int, error) {
time.Sleep(2 * time.Second)
return 2, nil
})
ctx, cancel := context.WithCancel(context.Background())
go func(){
time.Sleep(1 * time.Second)
cancel()
}()
//result, err, taskErrs := t.WaitAny(ctx)
result, err, taskErrs := t.Wait(ctx)
fmt.Println(result) //nil
fmt.Println(err) // context.Cancelled
fmt.Println(taskErrs) // nil
Contributions are welcome! If you're interested in contributing, please feel free to contribute