├── .gitignore ├── README.md ├── async.go ├── async_test.go ├── go.mod └── license.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vscode/ 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # async go 2 | 3 | a prototype of "promises" in go1.18. 4 | 5 | **note**: this is just an experiment used to test alternate patterns for dealing with asynchronous code in go. i would not recommend adopting this pattern blindly (especially in production environments) until there is a broader consensus in the go community about this. it might turn out that through some hands-on experience that go's native channels/goroutines are a good enough abstraction and there are no gains to be made from building on top of them. 6 | 7 | ## install 8 | 9 | should be just a regular package: 10 | 11 | ``` 12 | go get -u -v code.nkcmr.net/async@latest 13 | ``` 14 | 15 | ## usage 16 | 17 | promises abstract away a lot of details about how asynchronous work is handled. 18 | so if you need for something to be async, simply us a promise: 19 | 20 | ```go 21 | import ( 22 | "context" 23 | "code.nkcmr.net/async" 24 | ) 25 | 26 | type MyData struct {/* ... */} 27 | 28 | func AsyncFetchData(ctx context.Context, dataID int64) async.Promise[MyData] { 29 | return async.NewPromise(func() (MyData, error) { 30 | /* ... */ 31 | return myDataFromRemoteServer, nil 32 | }) 33 | } 34 | 35 | func DealWithData(ctx context.Context) { 36 | myDataPromise := AsyncFetchData(ctx, 451) 37 | // do other stuff while operation is not settled 38 | // once your ready to wait for data: 39 | myData, err := myDataPromise.Await(ctx) 40 | if err != nil {/* ... */} 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /async.go: -------------------------------------------------------------------------------- 1 | package async // import "code.nkcmr.net/async" 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | // Promise is an abstract representation of a value that might eventually be 8 | // delivered. 9 | type Promise[T any] interface { 10 | // Settled indicates if a call to Await will cause a blocking behavior, or 11 | // if the result will be immediately returned. 12 | Settled() bool 13 | 14 | // Await will cause the calling code to block and wait for the promise to 15 | // settle. Await MUST be able to be called by multiple goroutines and safely 16 | // deliver the same value/error to all waiting goroutines. Successive calls 17 | // to Await should continue to respond with the result even once the promise 18 | // is settled. 19 | Await(context.Context) (T, error) 20 | } 21 | 22 | type syncPromise[T any] struct { 23 | done chan struct{} 24 | v T 25 | err error 26 | } 27 | 28 | func (s *syncPromise[T]) Await(ctx context.Context) (T, error) { 29 | select { 30 | case <-ctx.Done(): 31 | var zerov T 32 | return zerov, ctx.Err() 33 | case <-s.done: 34 | return s.v, s.err 35 | } 36 | } 37 | 38 | func (s *syncPromise[T]) Settled() bool { 39 | select { 40 | case <-s.done: 41 | return true 42 | default: 43 | return false 44 | } 45 | } 46 | 47 | // NewPromise wraps a function in a goroutine that will make the result of that 48 | // function deliver its result to the holder of the promise. 49 | func NewPromise[T any](fn func() (T, error)) Promise[T] { 50 | c := &syncPromise[T]{ 51 | done: make(chan struct{}), 52 | } 53 | go func() { 54 | c.v, c.err = fn() 55 | close(c.done) 56 | }() 57 | return c 58 | } 59 | 60 | type rp[T any] struct { 61 | v T 62 | err error 63 | } 64 | 65 | func (r *rp[T]) Settled() bool { return true } 66 | 67 | func (r *rp[T]) Await(context.Context) (T, error) { 68 | return r.v, r.err 69 | } 70 | 71 | // Resolve wraps a value in a promise that will always be immediately settled 72 | // and return the provided value. 73 | func Resolve[T any](v T) Promise[T] { 74 | return &rp[T]{v: v} 75 | } 76 | 77 | // Reject wraps an error in a promise that will always be immediately settled 78 | // and return an error. 79 | func Reject[T any](err error) Promise[T] { 80 | return &rp[T]{err: err} 81 | } 82 | 83 | // All takes a slice of promises and will await the result of all of the 84 | // specified promises. If any promise should return an error, the wh 85 | func All[T any](ctx context.Context, promises []Promise[T]) ([]T, error) { 86 | var cancel context.CancelFunc 87 | ctx, cancel = context.WithCancel(ctx) 88 | defer cancel() 89 | out := make([]T, len(promises)) 90 | errc := make(chan error, len(out)) 91 | waiter := func(i int, p Promise[T]) { 92 | var err error 93 | out[i], err = p.Await(ctx) 94 | errc <- err 95 | } 96 | for i := range out { 97 | go waiter(i, promises[i]) 98 | } 99 | for i := 0; i < len(out); i++ { 100 | if err := <-errc; err != nil { 101 | cancel() 102 | return nil, err 103 | } 104 | } 105 | return out, nil 106 | } 107 | -------------------------------------------------------------------------------- /async_test.go: -------------------------------------------------------------------------------- 1 | package async 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "reflect" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestNewPromise(t *testing.T) { 12 | promise := NewPromise(func() (string, error) { 13 | time.Sleep(time.Millisecond * 500) 14 | return "foo", nil 15 | }) 16 | ctx := context.Background() 17 | v, err := promise.Await(ctx) 18 | requireEqual(t, true, promise.Settled()) 19 | requireNoError(t, err) 20 | requireEqual(t, "foo", v) 21 | 22 | promise = NewPromise(func() (string, error) { 23 | time.Sleep(time.Millisecond) 24 | return "", errors.New("darn") 25 | }) 26 | _, err = promise.Await(ctx) 27 | requireEqual(t, true, promise.Settled()) 28 | requireError(t, err) 29 | requireEqual(t, "darn", err.Error()) 30 | 31 | ctxlowtimeout, cancel := context.WithTimeout(ctx, time.Millisecond*50) 32 | defer cancel() 33 | promise = NewPromise(func() (string, error) { 34 | time.Sleep(time.Millisecond * 100) // should blow past the timeout 35 | return "too slow", nil 36 | }) 37 | _, err = promise.Await(ctxlowtimeout) 38 | requireEqual(t, false, promise.Settled()) // since it is probably still pending once we've timed out 39 | requireError(t, err) 40 | requireEqual(t, context.DeadlineExceeded, err) 41 | } 42 | 43 | func TestAll(t *testing.T) { 44 | promises := []Promise[int]{ 45 | NewPromise(func() (int, error) { 46 | return 42, nil 47 | }), 48 | NewPromise(func() (int, error) { 49 | time.Sleep(time.Millisecond * 50) 50 | return 43, nil 51 | }), 52 | NewPromise(func() (int, error) { 53 | time.Sleep(time.Millisecond * 100) 54 | return 44, nil 55 | }), 56 | } 57 | ctx := context.Background() 58 | ints, err := All(ctx, promises) 59 | requireNoError(t, err) 60 | requireEqual(t, []int{42, 43, 44}, ints) 61 | 62 | promises = []Promise[int]{ 63 | NewPromise(func() (int, error) { 64 | return 42, nil 65 | }), 66 | NewPromise(func() (int, error) { 67 | time.Sleep(time.Millisecond * 50) 68 | return 0, errors.New("doh!") 69 | }), 70 | } 71 | ints, err = All(ctx, promises) 72 | requireError(t, err) 73 | requireEqual(t, ints, nil) 74 | } 75 | 76 | func TestResolve(t *testing.T) { 77 | promise := Resolve("dff73ab5-5ff6-44f6-ba1e-7447ebf38675") 78 | if !promise.Settled() { 79 | t.Fatal("expected promise to be immediately resolved") 80 | return 81 | } 82 | ctx := context.Background() 83 | v, err := promise.Await(ctx) 84 | requireNoError(t, err) 85 | requireEqual(t, "dff73ab5-5ff6-44f6-ba1e-7447ebf38675", v) 86 | } 87 | 88 | func TestReject(t *testing.T) { 89 | promise := Reject[struct{}](errors.New("it failed. what can i say?")) 90 | if !promise.Settled() { 91 | t.Fatal("expected promise to be immediately rejected") 92 | return 93 | } 94 | ctx := context.Background() 95 | _, err := promise.Await(ctx) 96 | requireError(t, err) 97 | } 98 | 99 | func requireNoError(t *testing.T, err error) { 100 | t.Helper() 101 | if err != nil { 102 | t.Fatalf("unexpected error: %s", err.Error()) 103 | } 104 | } 105 | 106 | func requireError(t *testing.T, err error) { 107 | t.Helper() 108 | if err == nil { 109 | t.Fatalf("expected error, got nil") 110 | } 111 | } 112 | 113 | func requireEqual[T any](t *testing.T, expected, actual T) { 114 | t.Helper() 115 | if !reflect.DeepEqual(expected, actual) { 116 | t.Fatalf(`expected "%v" got "%v"`, expected, actual) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module code.nkcmr.net/async 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Nick Comer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------