promise

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2022 License: MIT Imports: 1 Imported by: 0

README

Promise

Go Promise Implementation with support for Generics (requires Go v1.18+).
Run async operations lazily in a separate goroutine on the fly.

Issues Stars License Stars Issues Twitter

Features

  • Easy interface for composing async operations
  • Executes a function in a separate goroutine
  • Error Handling using functions (also executed in a separate goroutine)
  • Support for Generics (requires Go v1.18+)
  • Promises are resolved lazily, upon a first call to Await, AwaitOr, Then, OnSuccess or onFailure
  • Support for promise.All and promise.Race (equivalent to the JavaScript Promise object)

Quickstart

package main

import (
	"log"
	"net/http"

	"github.com/felix-kaestner/promise"
)

func main() {
    // Create a new promise.
    // In this example the http request is executed in a separate goroutine
    p := promise.New(func() (*http.Response, error) {
        return http.Get("https://jsonplaceholder.typicode.com/posts/1")
    })
    
    // Handle successful and failed operations in a separate goroutine
    p.Then(func(res *http.Response) {
        log.Printf("Status: %s", res.Status)
    }, func(err error) {
        log.Fatalln(err)
    })

    // Handle only successful operations in a separate goroutine
    p.onSuccess(func(res *http.Response) {
        log.Printf("Status: %s", res.Status)
    })

    // Handle only failed operations in a separate goroutine
    p.onFailure(func(err error) {
        log.Fatalln(err)
    })

    // Await the promise.
    // This blocks execution until the promise is resolved.
    res, err := p.Await()
    
    // Provide a default value (calls Await() internally).
    res = p.AwaitOr(nil)

    // Use channels to select the awaited promise 
    select {
    case <-p.Done():
        res, err = p.Await() // returns immediately since the promise is already resolved
    case <-time.After(5000 * time.Millisecond):
        fmt.Println("Timeout")
    }

    // Take multiple promises and wait for all of them to be finished
    p1 := promise.New(func() (*http.Response, error) {
        return http.Get("https://jsonplaceholder.typicode.com/posts/1")
    })
    p2 := promise.New(func() (*http.Response, error) {
        return http.Get("https://jsonplaceholder.typicode.com/posts/2")
    })
    res, err := promise.All(p1, p2).Await()

    // Take multiple promises and wait until the first of them to is finished
    p1 := promise.New(func() (*http.Response, error) {
        return http.Get("https://jsonplaceholder.typicode.com/posts/3")
    })
    p2 := promise.New(func() (*http.Response, error) {
        return http.Get("https://jsonplaceholder.typicode.com/posts/4")
    })
    res, err := promise.Race(p1, p2).Await()

}

Installation

Install with the go get command:

$ go get -u github.com/felix-kaestner/promise

Contribute

All contributions in any form are welcome! 🙌
Just use the Issue and Pull Request templates and I will be happy to review your suggestions. 👍

Support

Any kind of support is well appreciated! 👏
If you want to tweet about the project, make sure to tag me @kaestner_felix. You can also support my open source work on GitHub Sponsors. All income will be directly invested in Coffee ☕!

Cheers ✌

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Promise

type Promise[T any] interface {
	// Await returns the result of the async operation.
	// If the operation has not completed it will block
	// until it does complete.
	// Otherwise it will return the result of the operation
	// immediately.
	Await() (T, error)

	// AwaitOr returns the result of the async operation
	// or a default value if the operation was not successful.
	AwaitOr(defaultValue T) T

	// Then executes the given functions when the promise
	// is either fulfilled or rejected respectively.
	// The functions are executed in a goroutine.
	Then(func(T), func(error))

	// OnSuccess executes the given function if the
	// promise is fulfilled.
	// The functions is executed in a goroutine.
	OnSuccess(func(T))

	// OnFailure executes the given function if the
	// promise is rejected.
	// The functions is executed in a goroutine.
	OnFailure(func(error))

	// Done returns a channel that's closed when the work done on behalf of this
	// promise is finished. Successive calls to Done return the same value.
	// The close of the Done channel may happen asynchronously,
	// after the function returns.
	//
	// Done is provided for use in select statements:
	//
	// // Produce generates a value by awaiting the promise and sending it to the out
	// // channel. It returns an error if the promise returned an error or ctx.Done is closed.
	// func Produce(ctx context.Context, p Promise[Value], out chan<- Value) error {
	// 	for {
	// 		select {
	// 		case <-ctx.Done():
	// 			return ctx.Err()
	// 		case <-p.Done():
	// 			v, err := p.Await() // returns immediately since the promise is already resolved
	// 			if err != nil {
	// 				return err
	// 			}
	// 			out <- v
	// 		}
	// 	}
	// }
	Done() <-chan struct{}
}

Promise is a object that can be used to get the result of an async operation.

func All added in v0.2.0

func All[T any](ps ...Promise[T]) Promise[[]T]

All takes multiple promises and returns a single promise, which will resolve to a slice of all the results of the promises.

If any of the promises fail, the returned promise will fail as well and contain the first error which occurred.

func New

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

New returns a new Promise of type T. The given function will be executed in a goroutine. The function should return the result of an async operation or an error if the operation failed.

func Race added in v0.2.0

func Race[T any](ps ...Promise[T]) Promise[T]

All takes multiple promises and returns a single promise, which will resolve to the value and error of the first promise that finishes execution.

Jump to

Keyboard shortcuts

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