All Projects → chebyrash → Promise

chebyrash / Promise

Licence: mit
Promise / Future library for Go

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Promise

Q
A platform-independent promise library for C++, implementing asynchronous continuations.
Stars: ✭ 179 (+20.13%)
Mutual labels:  promise, promises, futures
Bluebird Api
Bluebird compatible API on top of native promises.
Stars: ✭ 36 (-75.84%)
Mutual labels:  promise, promises
Functional Promises
Write code like a story w/ a powerful Fluent (function chaining) API
Stars: ✭ 141 (-5.37%)
Mutual labels:  promise, promises
Gollback
Go asynchronous simple function utilities, for managing execution of closures and callbacks
Stars: ✭ 55 (-63.09%)
Mutual labels:  promise, future
Then
🎬 Tame async code with battle-tested promises
Stars: ✭ 908 (+509.4%)
Mutual labels:  promise, future
Asynchronous
Implementation-agnostic asynchronous code
Stars: ✭ 13 (-91.28%)
Mutual labels:  promises, futures
Easyfutures
Easy Swift Futures & Promises.
Stars: ✭ 40 (-73.15%)
Mutual labels:  promises, futures
P Map
Map over promises concurrently
Stars: ✭ 639 (+328.86%)
Mutual labels:  promise, promises
Vine
Python promises
Stars: ✭ 83 (-44.3%)
Mutual labels:  promise, promises
Tomorrowland
Lightweight Promises for Swift & Obj-C
Stars: ✭ 106 (-28.86%)
Mutual labels:  promises, futures
Qtpromise
Promises/A+ implementation for Qt/C++
Stars: ✭ 137 (-8.05%)
Mutual labels:  promise, future
Minifuture
A monadic Future design pattern implementation in Swift
Stars: ✭ 16 (-89.26%)
Mutual labels:  promise, future
Future
🚀 R package: future: Unified Parallel and Distributed Processing in R for Everyone
Stars: ✭ 735 (+393.29%)
Mutual labels:  promises, futures
Promise.hpp
C++ asynchronous promises like a Promises/A+
Stars: ✭ 31 (-79.19%)
Mutual labels:  promise, promises
Swiftcoroutine
Swift coroutines for iOS, macOS and Linux.
Stars: ✭ 690 (+363.09%)
Mutual labels:  promises, futures
Breeze
Javascript async flow control manager
Stars: ✭ 38 (-74.5%)
Mutual labels:  promise, promises
Tascalate Concurrent
Implementation of blocking (IO-Bound) cancellable java.util.concurrent.CompletionStage and related extensions to java.util.concurrent.ExecutorService-s
Stars: ✭ 144 (-3.36%)
Mutual labels:  promise, promises
Lwt
OCaml promises and concurrent I/O
Stars: ✭ 505 (+238.93%)
Mutual labels:  promises, futures
Posterus
Composable async primitives with cancelation, control over scheduling, and coroutines. Superior replacement for JS Promises.
Stars: ✭ 536 (+259.73%)
Mutual labels:  promise, future
Pinfuture
An Objective-C future implementation that aims to provide maximal type safety
Stars: ✭ 74 (-50.34%)
Mutual labels:  promises, futures

PROMISE

Go Report Card Build Status Go Reference

About

Promises library for Golang. Inspired by JS Promises

Supports:

• Automatic panic recovery

• Nested promise flattening

• Promise cancellation

You can use promise.Any as a substitute for interface{} until generics arrive in Go and the library is updated.

Install

$ go get -u github.com/chebyrash/promise

Quick Start

var p = promise.New(func(resolve func(promise.Any), reject func(error)) {
  // Do something asynchronously.
  const sum = 2 + 2

  // If your work was successful call resolve() passing the result.
  if sum == 4 {
    resolve(sum)
    return
  }

  // If you encountered an error call reject() passing the error.
  if sum != 4 {
    reject(errors.New("2 + 2 doesnt't equal 4"))
    return
  }

  // If you forgot to check for errors and your function panics the promise will
  // automatically reject.
  // panic() == reject()
}).
  // You may continue working with the result of
  // a previous async operation.
  Then(func(data promise.Any) promise.Any {
    fmt.Println("The result is:", data)
    return data.(int) + 1
  }).

  // Handlers can be added even after the success or failure of the asynchronous operation.
  // Multiple handlers may be added by calling .Then or .Catch several times,
  // to be executed independently in insertion order.
  Then(func(data promise.Any) promise.Any {
    fmt.Println("The new result is:", data)
    return nil
  }).
  Catch(func(err error) error {
    fmt.Println("Error during execution:", err.Error())
    return nil
  })

// Since handlers are executed asynchronously you can wait for them.
p.Await()

Methods

All

Wait for all promises to be resolved, or for any to be rejected. If the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises in the same order as defined in the iterable of multiple promises. If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected.

Example:

var p1 = promise.Resolve(123)
var p2 = promise.Resolve("Hello, World")
var p3 = promise.Resolve([]string{"one", "two", "three"})

results, _ := promise.All(p1, p2, p3).Await()
fmt.Println(results)
// [123 Hello, World [one two three]]

AllSettled

Wait until all promises have settled (each may resolve, or reject). Returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.

Example:

var p1 = promise.Resolve(123)
var p2 = promise.Reject(errors.New("something wrong"))

results, _ := promise.AllSettled(p1, p2).Await()
for _, result := range results.([]promise.Any) {
    switch value := result.(type) {
    case error:
        fmt.Printf("Bad error occurred: %s", value.Error())
    default:
        fmt.Printf("Other result type: %d", value.(int))
    }
}
// Other result type: 123
// Bad error occurred: something wrong

Race

Wait until any of the promises is resolved or rejected. If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved. If it rejects, it is rejected with the reason from the first promise that was rejected.

Example:

var p1 = promise.Resolve("Promise 1")
var p2 = promise.Resolve("Promise 2")

fastestResult, _ := promise.Race(p1, p2).Await()

fmt.Printf("Both resolve, but %s is faster", fastestResult)
// Both resolve, but Promise 1 is faster
// OR
// Both resolve, but Promise 2 is faster

Resolve

Returns a new Promise that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Example:

var p1 = promise.Resolve("Hello, World")
result, _ := p1.Await()
fmt.Println(result)
// Hello, World

Reject

Returns a new Promise that is rejected with the given reason.

Example:

var p1 = promise.Reject(errors.New("bad error"))
_, err := p1.Await()
fmt.Println(err)
// bad error

Examples

HTTP Request

var requestPromise = promise.New(func(resolve func(promise.Any), reject func(error)) {
  resp, err := http.Get("https://httpbin.org/ip")
  defer resp.Body.Close()
  if err != nil {
    reject(err)
    return
  }

  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    reject(err)
    return
  }
  resolve(body)
})

// Parse JSON body in async manner
parsed, err := requestPromise.
  Then(func(data promise.Any) promise.Any {
    // This can be a promise, it will automatically flatten
    return parseJSON(data.([]byte))
  }).Await()

if err != nil {
  fmt.Printf("Error: %s\n", err.Error())
  return
}

origin := parsed.(map[string]string)["origin"]
fmt.Printf("Origin: %s\n", origin)

Finding Factorial

func findFactorial(n int) int {
	if n == 1 {
		return 1
	}
	return n * findFactorial(n-1)
}

func findFactorialPromise(n int) *promise.Promise {
	return promise.Resolve(findFactorial(n))
}

func main() {
	var factorial1 = findFactorialPromise(5)
	var factorial2 = findFactorialPromise(10)
	var factorial3 = findFactorialPromise(15)

	// Results calculated asynchronously
	results, _ := promise.All(factorial1, factorial2, factorial3).Await()
	values := results.([]promise.Any)

	fmt.Println("Result of 5! is", values[0])
	fmt.Println("Result of 10! is", values[1])
	fmt.Println("Result of 15! is", values[2])
}

Chaining

var p = promise.Resolve(nil).
  Then(func(data promise.Any) promise.Any {
    fmt.Println("I will execute first")
    return nil
  }).
  Then(func(data promise.Any) promise.Any {
    fmt.Println("And I will execute second!")
    return nil
  }).
  Then(func(data promise.Any) promise.Any {
    fmt.Println("Oh I'm last :(")
    return nil
  })

p.Await()
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].