Documentation
¶
Overview ¶
Package async provides asynchronous orchestration primitives for Go: promises, futures, and deferred actions.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Future ¶
type Future[T any] struct { // contains filtered or unexported fields }
Future represents a read-only view of a promised value. It provides a way to retrieve the value asynchronously, blocking if necessary.
type FutureAction ¶
type FutureAction[T any] struct { // contains filtered or unexported fields }
FutureAction is an abstraction over a channel that models a task and its result. It allows executing a computation asynchronously in a goroutine and retrieving the result later via a blocking call. This is similar to the Future pattern in other languages, providing a simple way to handle asynchronous results without manual channel management.
The channel is closed after the result is sent, ensuring proper resource cleanup.
Example usage:
func main() {
callback := func() any {
time.Sleep(time.Second)
return "success"
}
future := NewFutureAction(callback)
result := future.Get()
fmt.Println(result) // Output: success
}
func NewFutureAction ¶
func NewFutureAction[T any](action func() T) *FutureAction[T]
NewFutureAction creates and returns a new FutureAction. It starts the provided action function in a separate goroutine. The action's return value is sent to the internal channel. The channel is closed after sending the result to allow safe ranging or detection of completion.
func (*FutureAction[T]) Get ¶
func (f *FutureAction[T]) Get() T
Get returns the result of the asynchronous task. This method blocks until the result is available from the channel. If the action function blocks indefinitely (e.g., due to an infinite loop or deadlock), Get will never return, potentially causing the caller to hang. It is the caller's responsibility to ensure the action completes.
type FutureError ¶
FutureError is a Future specialized for error propagation.
type Promise ¶
type Promise[T any] struct { // contains filtered or unexported fields }
Promise represents a writable, single-assignment container for a future value. It allows setting a value exactly once. Attempting to set the value more than once is ignored. The internal channel is buffered to hold one value and is closed after setting. Synchronization is handled via atomic operations for thread safety.
Example usage:
func main() {
promise := NewPromise[string]()
go func() {
time.Sleep(time.Second)
promise.Set("Cake")
}()
future := promise.GetFuture()
value := future.Get()
fmt.Println(value) // Output: Cake
}
func NewPromise ¶
NewPromise creates and returns a new Promise. The internal channel is buffered with capacity 1 to hold the future value.
type PromiseError ¶
PromiseError is a Promise specialized for error propagation.