package future
import (
"context"
"fmt"
)
type ValueFutureResolver [V any ] func (value V , err error )
type ValueFuture [V any ] struct {
ctx context .Context
}
func (f *ValueFuture [V ]) Done () <-chan struct {} {
return f .ctx .Done ()
}
func (f *ValueFuture [V ]) Result () (V , error ) {
<-f .ctx .Done ()
cause := context .Cause (f .ctx )
if cause != nil {
if resolution , ok := cause .(*valueFutureResolution [V ]); ok {
return resolution .value , resolution .err
}
}
var zero V
return zero , cause
}
func (f *ValueFuture [V ]) Wait () (V , error ) {
return f .Result ()
}
func NewValueFuture [V any ](ctx context .Context ) (*ValueFuture [V ], ValueFutureResolver [V ]) {
childCtx , cancel := context .WithCancelCause (ctx )
future := &ValueFuture [V ]{
ctx : childCtx ,
}
return future , func (value V , err error ) {
cancel (&valueFutureResolution [V ]{
value : value ,
err : err ,
})
}
}
type valueFutureResolution[V any ] struct {
value V
err error
}
func (v *valueFutureResolution [V ]) Error () string {
if v .err != nil {
return v .err .Error()
}
return fmt .Sprintf ("future resolved: %#v" , v .value )
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .