-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement.go
91 lines (90 loc) · 2.02 KB
/
implement.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package async
func race(promises *Tasks) *GoPromise {
var newPromise *GoPromise
newPromise = Promise(func(resolve, reject Handler) {
for _, promise := range *promises {
go func(promise *GoPromise) {
ret, err := promise.UnsafeAwait()
if newPromise.settled() {
return
}
if err == nil {
resolve(ret)
} else {
reject(err)
}
}(promise)
}
})
return newPromise
}
func all(promises *Tasks) *GoPromise {
num := len(*promises)
result := make([]interface{}, num)
count := safeAct()
var newPromise *GoPromise
newPromise = Promise(func(resolve, reject Handler) {
for i, promise := range *promises {
go func(i int, promise *GoPromise) {
ret, err := promise.UnsafeAwait()
if newPromise.settled() {
return
}
if err == nil {
count.do(func(c *counter) {
result[i] = ret
c.count++
})
if count.value() == num {
resolve(result)
}
} else {
reject(err)
}
}(i, promise)
}
})
return newPromise
}
func allSettled(promises *Tasks) *GoPromise {
return Promise(func(resolve, reject Handler) {
result := make([]*Settled, len(*promises))
for i, promise := range *promises {
ret, err := promise.UnsafeAwait()
if err == nil {
result[i] = &Settled{Resolved, ret}
} else {
result[i] = &Settled{Rejected, err}
}
}
resolve(result)
})
}
func any(promises *Tasks) *GoPromise {
num := len(*promises)
result := make([]interface{}, num)
count := safeAct()
var newPromise *GoPromise
newPromise = Promise(func(resolve, reject Handler) {
for i, promise := range *promises {
go func(i int, promise *GoPromise) {
ret, err := promise.UnsafeAwait()
if newPromise.settled() {
return
}
if err != nil {
count.do(func(c *counter) {
result[i] = err
c.count++
})
if count.value() == num {
reject(result)
}
} else {
resolve(ret)
}
}(i, promise)
}
})
return newPromise
}