forked from ianlopshire/go-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
75 lines (59 loc) · 1.4 KB
/
example_test.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package async_test
import (
"fmt"
"log"
"time"
"github.com/ianlopshire/go-async"
)
func ExampleFuture() {
// Create a new Future
fut := new(async.Future[string])
// Simulate long computation or IO by sleeping before setting the value and resolving
// the future.
go func() {
time.Sleep(500 * time.Millisecond)
async.ResolveFuture(fut, "Hello World!", nil)
}()
// Block until the Future is resolved.
v, err := fut.Value()
if err != nil {
log.Fatal(err)
}
fmt.Println(v, err)
// output: Hello World! <nil>
}
func ExampleFuture_select() {
fut := new(async.Future[string])
// The channel returned by Done() can be used directly in a select statement.
select {
case <-fut.Done():
fmt.Println(fut.Value())
default:
fmt.Println("Future not yet resolved")
}
// output: Future not yet resolved
}
func ExampleLatch() {
l := new(async.Latch)
// Simulate long computation or IO by sleeping before setting the value and resolving
// the future.
go func() {
time.Sleep(500 * time.Millisecond)
async.Resolve(l, nil)
}()
// Block until the Latch is resolved.
async.Await(l)
fmt.Println("Done!")
// output: Done!
}
func ExampleLatch_select() {
l := new(async.Latch)
// The channel returned by Done() can be used directly in a select statement.
select {
case <-l.Done():
fmt.Println("Done!")
default:
fmt.Println("Latch not yet resolved")
}
// output: Latch not yet resolved
}