Async / Await
The most basic functionality of the package is async/await pattern. It allows you to run functions in parallel and wait for their completion.
Please note, that async functions are not concurrent, they are parallel. It's important because you still have to be careful with shared resources.
go
// Example of async function.
func mult(n int) *async.Future[int] {
return async.New(func() (int, error) {
time.Sleep(time.Second)
return n * 2, nil
})
}
// We will use this future to demonstrate resolving.
ftr := mult(2)
// We have multiple ways to handle future resolving.
// One of them is to use Then/Catch methods.
// Then is called on execution completion, Catch is called when future has an error.
ftr.Then(func(val int) {
fmt.Println("Resolved:", val)
}).Catch(func(err error) {
fmt.Println("Error:", err)
})
// Another way is to use Await method.
// It will block until future is resolved.
val, err := ftr.Await()
// We also have an async.Await function if you prefer functional style.
val, err := async.Await(ftr)