2

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?

1
  • Thank you so much for the great and detailed answers, imike and johannes-weiss. Unfortunately SO doesn't have a way of marking both answers as the right answer, or I would have. Commented Jun 6, 2020 at 7:57

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.