-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise_group.go
49 lines (41 loc) · 937 Bytes
/
promise_group.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 std
import (
"github.com/pkg/errors"
"sync"
)
type PromiseId string
type PromiseGroup struct {
hangs map[PromiseId]Promise
lock sync.Locker
}
func NewPromiseGroup() *PromiseGroup {
ret := &PromiseGroup{
hangs: make(map[PromiseId]Promise),
lock: &sync.Mutex{},
}
return ret
}
func (this *PromiseGroup) DonePromise(id PromiseId, err error, data interface{}) {
defer this.lock.Unlock()
this.lock.Lock()
if c, ok := this.hangs[id]; ok {
c.DoneData(err, data)
}
delete(this.hangs, id)
}
var ErrPromiseReplace = errors.New("this promise has been replace by another one!")
func (this *PromiseGroup) AddPromise(id PromiseId, c Promise) {
defer this.lock.Unlock()
this.lock.Lock()
old, ok := this.hangs[id]
if !ok {
this.hangs[id] = c
return
}
old.Done(ErrPromiseReplace)
}
func (this *PromiseGroup) RemovePromise(id PromiseId) {
defer this.lock.Unlock()
this.lock.Lock()
delete(this.hangs, id)
}