Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all values for [EventLoopFuture] before proceeding

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?

like image 295
niklassaers Avatar asked Jul 03 '26 05:07

niklassaers


2 Answers

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)
like image 156
Johannes Weiss Avatar answered Jul 05 '26 18:07

Johannes Weiss


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

like image 30
imike Avatar answered Jul 05 '26 19:07

imike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!