-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
57 lines (48 loc) · 1.72 KB
/
promise.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright 2023-2024 Oliver Eikemeier. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package promise
// Promise is used to send the result of an asynchronous operation.
//
// It is a write-only channel.
// Either [Promise.Resolve] or [Promise.Reject] should be called exactly once.
type Promise[R any] chan<- Result[R]
// New provides a simple way to create a [Promise] for asynchronous operations.
// This allows synchronous and asynchronous code to be composed seamlessly and separating initiation from running.
//
// The returned [Future] can be used to retrieve the eventual result of the [Promise].
func New[R any]() (Promise[R], Future[R]) {
ch := make(chan Result[R], 1)
return ch, ch
}
// Resolve fulfills the promise with a value.
func (p Promise[R]) Resolve(value R) {
p.complete(Result[R]{Value: value})
}
// Reject breaks the promise with an error.
func (p Promise[R]) Reject(err error) {
p.complete(Result[R]{Err: err})
}
// Do runs f synchronously, resolving the promise with the return value.
func (p Promise[R]) Do(f func() (R, error)) {
p.complete(NewResult(f()))
}
func (p Promise[R]) complete(r Result[R]) {
if p == nil {
return
}
p <- r
close(p)
}