Documentation ¶
Overview ¶
Package promise builds something similar to JS style promises, or Futures(as seen in Java and other languages) for golang.
promise is type-safe at runtime, and within an order of magnitude of performance of a solution built with pure channels and goroutines.
For a more thorough introduction to the library, please check out https://github.com/garlicnation/promises/blob/master/blog_example/WHY.md
Examples ¶
Single promise:
p := promise.New(func() int { return 1 }) var resolved int err := p.Wait(&resolved)
Chained Promise:
p := promise.New(func() int { return 1 }) timesTwo := p.Then(func(x int) int { return x*2 }) var resolved int err := timesTwo.Wait(&resolved)
Promise.all:
p := promise.New(func() int { return 1 }) timesTwo := p.Then(func(x int) int { return x * 2 }) plusFour := timesTwo.Then(func(x int) int{ return x + 4 }) all := promise.All(p, timesTwo, plusFour) results := []int{} err := all.Wait(&results)
Error handling:
p := promise.New(http.Get, "http://example.com") // Do other work while Get processes in a goroutine... var r *http.Response err := p.Wait(&r) // Errors are swallowed by promise and returned by wait.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AnyErr ¶
type AnyErr struct { // Errs contains the error of all passed promises Errs []error // LastErr contains the error of the last promise to fail. LastErr error }
AnyErr returns when all promises passed to Any fail
type Promise ¶
type Promise struct {
// contains filtered or unexported fields
}
A Promise represents an asynchronously executing unit of work
Example (Chain) ¶
p := New(func() int { fmt.Println("second") time.Sleep(50 * time.Millisecond) return 7 }) pByTwo := p.Then(func(x int) int { fmt.Println("fifth") time.Sleep(100 * time.Millisecond) return x * 2 }) pByFour := p.Then(func(x int) int { fmt.Println("third") time.Sleep(50 * time.Millisecond) return x * 4 }) var resOne, resTwo int fmt.Println("First this happens") err := pByTwo.Wait(resOne) if err != nil { panic(err) } fmt.Println("fourth") err = pByFour.Wait(&resTwo) if err != nil { panic(err) } fmt.Println("sixth")
Output:
func All ¶
All returns a promise that resolves if all of the passed promises succeed or fails if any of the passed promises panics.
func Any ¶
Any returns a promise that resolves if any of the passed promises succeed or fails if all of the passed promises panics. All of the supplied promises must be of the same type.
func New ¶
func New(f interface{}, args ...interface{}) *Promise
New returns a promise that resolves when f completes. Any panic() encountered will be returned as an error from Wait()
func Race ¶
Race returns a promise that resolves if any of the passed promises succeed or fails if any of the passed promises panics. All of the supplied promises must be of the same type.