forked from lovoo/goka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
57 lines (47 loc) · 1.05 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
package kafka
import "sync"
// Promise as in https://en.wikipedia.org/wiki/Futures_and_promises
type Promise struct {
sync.Mutex
err error
finished bool
callbacks []func(err error)
}
// NewPromise creates a new Promise
func NewPromise() *Promise {
return new(Promise)
}
// execute all callbacks conveniently
// The caller needs to lock!
func (p *Promise) executeCallbacks() {
// already resolved
if p.finished {
return
}
for _, s := range p.callbacks {
s(p.err)
}
// mark as finished
p.finished = true
}
// Then chains a callback to the Promise
func (p *Promise) Then(s func(err error)) *Promise {
p.Lock()
defer p.Unlock()
// promise already run, call the callback immediately
if p.finished {
s(p.err)
// append it to the subscribers otherwise
} else {
p.callbacks = append(p.callbacks, s)
}
return p
}
// Finish finishes the promise by executing all callbacks and saving the message/error for late subscribers
func (p *Promise) Finish(err error) *Promise {
p.Lock()
defer p.Unlock()
p.err = err
p.executeCallbacks()
return p
}