I have an array of values I map to multiple promises that give me each a EventLoopFuture. So I end up with a method that has a variable-size [EventLoopFuture], and I need all the responses to succeed before I can continue. If one or more of them returns an error, I need to perform the error scenario.
How can I await the entire [EventLoopFuture] to complete before continuing with either the succeed path or error path?
EventLoopFuture's got a reduce(into: ...) method that can be used quite well for that purpose (and other tasks where you want to accumulate multiple values):
let futureOfStrings: EventLoopFuture<[String]> =
EventLoopFuture<String>.reduce(into: Array<String>(),
futures: myArrayFutureStrings,
on: someEventLoop,
{ array, nextValue in array.append(nextValue) })
To specifically turn [EventLoopFuture<Something>] into EventLoopFuture<[Something]> you can also use the shorter whenAllSucceed
let futureOfStrings: EventLoopFuture<[String]> =
EventLoopFuture<String>.whenAllSucceed(myStringFutures, on: someEventLoop)
Waiting for all futures in array is possible with flatten like this
[future1, future2, future3, future4].flatten(on: eventLoop)
for flatten each future should return Void and flatten itself will return EventLoopFuture<Void>
sometimes we need to process some array with simple values and do something with each value using some method which returns EventLoopFuture and in this case the code may look like this
let array = ["New York", "Los Angeles", "Las Vegas"]
array.map { city in
someOtherMethod(city).transform(to: ())
}.flatten(on: eventLoop)
in the example above method someOtherMethod can return future with anything but we can transform it to EventLoopFuture<Void> to use with flatten
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With