future

package module
v0.0.0-...-92edfa0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 12, 2025 License: MIT Imports: 0 Imported by: 0

README

Future

A Future is a basic primitive for managing future results of any type. The result can be set once but retrieved multiple times.

Example

package main

import (
	"fmt"
	"github.com/gavraz/async/future"
	"time"
)

func makePromise() *future.Future[int] {
	p := future.NewPromise[int]()

	go func() {
		time.Sleep(2 * time.Second)
		p.Set(42)
	}()

	return p.Future()
}

func main() {
	f := makePromise()

	go func() {
		select {
		// ...
		case <-f.Done():
		}
		fmt.Println("Done waiting for result")
	}()

	fmt.Println("Result:", f.Value())

	// output:
	// Done waiting for result
	// Result: 42
}

Documentation

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 is used to wait for a value that may be available in the future. Callers may use Done to wait in a select statement.

func (*Future[T]) Done

func (f *Future[T]) Done() <-chan struct{}

Done is a channel used in select statements to wait until the value is available.

func (*Future[T]) Value

func (f *Future[T]) Value() T

Value blocks until the value is set and then returns it. If the result is already set, it returns immediately.

type Promise

type Promise[T any] struct {
	// contains filtered or unexported fields
}

Promise is used to commit for value. The promised value can be set using Set and be retrieved using Future.

func NewPromise

func NewPromise[T any]() *Promise[T]

func (*Promise[T]) Future

func (p *Promise[T]) Future() *Future[T]

func (*Promise[T]) Set

func (p *Promise[T]) Set(result T)

Set assigns a value to the future and makes it available to waiting routines. The result can be set only once.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL