Skip to content

Commit 70433c1

Browse files
committed
Added flatten(on) from Vapor
1 parent edf83a9 commit 70433c1

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

Sources/GraphQL/Utilities/Dictionary+FutureType.swift

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ extension EventLoopFuture: FutureType {
3232

3333
/// See `FutureType`.
3434
public func addAwaiter(callback: @escaping (FutureResult<T>) -> ()) {
35-
self.do { result in
35+
_ = self.map { result in
3636
callback(.success(result))
37-
}.catch { error in
37+
}.mapIfError { error in
3838
callback(.error(error))
3939
}
4040
}
@@ -76,16 +76,49 @@ public indirect enum FutureResult<T> {
7676
}
7777
}
7878

79+
extension Collection where Element : FutureType {
80+
/// Flattens an array of futures into a future with an array of results.
81+
/// note: the order of the results will match the order of the
82+
/// futures in the input array.
83+
///
84+
/// [Learn More →](https://docs.vapor.codes/3.0/async/advanced-futures/#combining-multiple-futures)
85+
public func flatten(on worker: EventLoopGroup) -> EventLoopFuture<[Element.Expectation]> {
86+
guard count > 0 else {
87+
return worker.next().newSucceededFuture(result: [])
88+
}
89+
var elements: [Element.Expectation] = []
90+
91+
let promise: EventLoopPromise<[Element.Expectation]> = worker.next().newPromise()
92+
elements.reserveCapacity(self.count)
93+
94+
for element in self {
95+
element.addAwaiter { result in
96+
switch result {
97+
case .error(let error): promise.fail(error: error)
98+
case .success(let expectation):
99+
elements.append(expectation)
100+
101+
if elements.count == self.count {
102+
promise.succeed(result: elements)
103+
}
104+
}
105+
}
106+
}
107+
108+
return promise.futureResult
109+
}
110+
}
111+
79112
/// !! From Vapor Async end
80113

81114
extension Dictionary where Value: FutureType {
82115
func flatten(on worker: EventLoopGroup) -> EventLoopFuture<[Key: Value.Expectation]> {
83-
var elements: [Key: Value.Expectation] = [:]
84-
85116
guard self.count > 0 else {
86-
return worker.next().newSucceededFuture(result: elements)
117+
return worker.next().newSucceededFuture(result: [:])
87118
}
88119

120+
var elements: [Key: Value.Expectation] = [:]
121+
89122
let promise: EventLoopPromise<[Key: Value.Expectation]> = worker.next().newPromise()
90123
elements.reserveCapacity(self.count)
91124

0 commit comments

Comments
 (0)