-
Notifications
You must be signed in to change notification settings - Fork 11
/
future_utils.go
53 lines (49 loc) · 1.26 KB
/
future_utils.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
package async
import (
"fmt"
"time"
)
// FutureSeq reduces many Futures into a single Future.
// The resulting array may contain both T values and errors.
func FutureSeq[T any](futures []Future[T]) Future[[]any] {
next := newFuture[[]any]()
go func() {
seq := make([]any, len(futures))
for i, future := range futures {
result, err := future.Join()
if err != nil {
seq[i] = err
} else {
seq[i] = result
}
}
next.complete(seq, nil)
}()
return next
}
// FutureFirstCompletedOf asynchronously returns a new Future to the result
// of the first Future in the list that is completed.
// This means no matter if it is completed as a success or as a failure.
func FutureFirstCompletedOf[T any](futures ...Future[T]) Future[T] {
next := newFuture[T]()
go func() {
for _, f := range futures {
go func(future Future[T]) {
next.complete(future.Join())
}(f)
}
}()
return next
}
// FutureTimer returns Future that will have been resolved after given duration;
// useful for FutureFirstCompletedOf for timeout purposes.
func FutureTimer[T any](d time.Duration) Future[T] {
next := newFuture[T]()
go func() {
<-time.After(d)
var zero T
next.(*futureImpl[T]).
complete(zero, fmt.Errorf("future timeout after %s", d))
}()
return next
}