promise

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package promise provides a Go way to represent the concept of a Promise.

In JavaScript, a promise represents an operation that will fulfill with a value in the future, or produce an error. The outcome of the operation is represented by generic type Result, containing either an error or a fulfilled value. The generic Promise type is just a channel where the value will be received.

This package is not intended to provide be a full implementation of JavaScript promises. The intention is to simplify implementation of web APIs that returns promises, e.g. the fetch API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrAny

type ErrAny struct{ Reason any }

ErrAny wraps any value as a valid go [error] value. While errors originating from Go code will always be instances of error, in JavaScript, any value can be an error.

When an error is generated in JavaScript code, and not representable directly as an error in Go, ErrAny will represent the value.

TODO: This isn't specific to promises, but there's not really another package that's a good fit ATM, and I don't want to create a new package just to have this type. Consider moving in the future

func (ErrAny) As

func (err ErrAny) As(target any) bool

func (ErrAny) Error

func (err ErrAny) Error() string

type Promise

type Promise[T any] chan Result[T]

func New

func New[T any](f func() (T, error)) Promise[T]

New returns a promise. If function f is non-nil, it will be executed in a separate gorouting, and the promise will eventually settle with the result of the function. If f returns a non-nil error, the promise will reject, otherwise it will resolve with a value of type T.

func ReadAll

func ReadAll(reader io.Reader) Promise[[]byte]

func (Promise[T]) Close

func (p Promise[T]) Close()

func (Promise[T]) Reject

func (p Promise[T]) Reject(err error)

Reject rejects the promise,

func (Promise[T]) Resolve

func (p Promise[T]) Resolve(v T)

func (Promise[T]) Send

func (p Promise[T]) Send(v T, err error)

type Result

type Result[T any] struct {
	Value T
	Err   error
}

Result represents the outcome of a promise. If the promise is rejected, Err will contain a non-nil value. If Err is nil, the promise was fulfilled, the result contained in field Value.

Jump to

Keyboard shortcuts

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