forked from ianlopshire/go-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.go
49 lines (42 loc) · 1.14 KB
/
async.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
// Package async provides asynchronous primitives and utilities.
package async
import (
"context"
"errors"
)
// ErrAlreadyResolved indicates that a Resolver has already been resolved.
var ErrAlreadyResolved = errors.New("async: already resolved")
// Awaiter is an interface that can await a resolution.
type Awaiter interface {
Done() <-chan struct{}
}
// Await blocks until r is resolved.
//
// synonymous with:
// <-a.Done()
func Await(a Awaiter) {
<-a.Done()
}
// AwaitCtx blocks until a is resolved or the context is canceled.
func AwaitCtx(ctx context.Context, a Awaiter) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-a.Done():
return nil
}
}
// Resolver is an interface that wraps the unexported resolve method.
//
// It is implemented by Latch and can also be implemented by embedding Latch into a custom
// type.
type Resolver interface {
resolve(func())
}
// Resolve resolves a Resolver and runs the given function. It is guaranteed that fn will
// be call at most once.
//
// Calling Resolve more than once for a single Resolver will panic with ErrAlreadyResolved.
func Resolve(r Resolver, fn func()) {
r.resolve(fn)
}