View client5.go
func main() {
c, _ := context.WithTimeout(context.Background(), 1*time.Second)
a := 10
f := future.NewWithContext(c, func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
val, err := f.Get()
View new_context.go
func NewWithContext(ctx context.Context, inFunc Process) Interface {
f := New(inFunc).(*futureImpl)
c := ctx.Done()
if c != nil {
go func() {
select {
case <-c:
//if context is cancelled, cancel future
f.Cancel()
case <-f.cancel:
View client4.go
func main() {
a := 10
f := future.New(func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
go func() {
time.Sleep(1 * time.Second)
View updated_new_then_get_get_until.go
func New(inFunc Process) Interface {
return newInner(make(chan struct{}), &sync.Once{}, inFunc)
}
func newInner(cancelChan chan struct{}, o *sync.Once, inFunc Process) Interface {
f := futureImpl{
done: make(chan struct{}),
cancel: cancelChan,
o: o,
}
View futureImpl2.go
type futureImpl struct {
done chan struct{}
cancel chan struct{}
val interface{}
err error
o *sync.Once
}
func (f *futureImpl) Cancel() {
select {
View future4.go
// Interface represents a future. No concrete implementation is
// exposed; all access to a future is via this interface.
type Interface interface {
// Get returns the values calculated by the future. It will pause until
// the value is calculated.
//
// If Get is invoked multiple times, the same value will be returned each time.
// Subsequent calls to Get will return instantaneously.
//
// When the future is cancelled, nil is returned for both the value and the error.
View client3.go
func main() {
a := 10
f := future.New(func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
// this will wait for a second to complete
// and will return nil for both val and err
View then1.go
func (f *futureImpl) Then(next Step) Interface {
nextFuture := New(func() (interface{}, error) {
result, err := f.Get()
if err != nil {
return result, err
}
return next(result)
})
return nextFuture
}
View future3.go
// Interface represents a future. No concrete implementation is
// exposed; all access to a future is via this interface.
type Interface interface {
// Get returns the values calculated by the future. It will pause until
// the value is calculated.
//
// If Get is invoked multiple times, the same value will be returned each time.
// Subsequent calls to Get will return instantaneously.
Get() (interface{}, error)
View client2.go
func main() {
a := 10
f := future.New(func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
})
// this will wait for a second to complete
// and will return nil for both val and err
// and timeout will be true
val, timeout, err := f.GetUntil(1 * time.Second)