项目作者: martinohmann

项目描述 :
Implementation of the Promises/A+ Standard in Go
高级语言: Go
项目地址: git://github.com/martinohmann/promise.git
创建时间: 2019-12-20T13:45:12Z
项目社区:https://github.com/martinohmann/promise

开源协议:MIT License

下载


Promise

Build Status
codecov
GoDoc
Go Report Card
GitHub

Initially this started out as an experiment to better understand the inner workings of
JavaScript promises and how this can be implemented from scratch in go.

The result is a promise implementation which follows the Promises/A+
Standard
and comes with the following additional
features:

  • Waiting for promise resolution.
  • Panics during promise resolution cause the promise to be rejected with the
    panic message.
  • Nested promise resolution.
  • Race, All, Any and AllSettled extensions to handle the parallel
    resolution of multiple promises.
  • Promise pooling. See the promise.Pool
    documentation

    and the pooling example.
  • Promise instrumentation for tracing, logging and debugging. See the
    instrumented package
    documentation

    for more information.

Head over to the promise
godoc
for the API
documentation.

Installation

  1. go get -u github.com/martinohmann/promise

Usage

Check out the examples in the _examples/ directory to see promises in action.

Simple example

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "github.com/martinohmann/promise"
  8. )
  9. func init() {
  10. rand.Seed(time.Now().UnixNano())
  11. }
  12. func main() {
  13. p := promise.New(func(resolve promise.ResolveFunc, reject promise.RejectFunc) {
  14. // simulate some computation
  15. sleepDuration := time.Duration(rand.Int63n(2000)) * time.Millisecond
  16. time.Sleep(sleepDuration)
  17. fmt.Printf("computation took %s\n", sleepDuration)
  18. // inject some random errors
  19. if rand.Int63n(2) == 0 {
  20. reject(errors.New("computation failed"))
  21. return
  22. }
  23. // simulate computation result
  24. resolve(rand.Int63())
  25. }).Then(func(val promise.Value) promise.Value {
  26. fmt.Printf("computation result: %d\n", val.(int64))
  27. return val
  28. }).Catch(func(err error) promise.Value {
  29. fmt.Printf("error during computation: %v\n", err)
  30. return err
  31. })
  32. // Wait for the promise resolution to be complete, that is: either fulfillment or rejection.
  33. val, err := p.Await()
  34. if err != nil {
  35. fmt.Printf("Promise rejected with error: %v\n", err)
  36. } else {
  37. fmt.Printf("Promise fulfilled with value: %d\n", val.(int64))
  38. }
  39. }

License

The source code of promise is released under the MIT License. See the bundled
LICENSE file for details.