2

我有一组值映射到多个 Promise,每个 Promise 都给我一个 EventLoopF​​uture。所以我最终得到了一个具有可变大小 [EventLoopF​​uture] 的方法,并且我需要所有响应都成功才能继续。如果其中一个或多个返回错误,我需要执行错误场景。

在继续使用成功路径或错误路径之前,如何等待整个 [EventLoopF​​uture] 完成?

4

2 回答 2

8

EventLoopFuture有一个reduce(into: ...)可以很好地用于该目的的方法(以及您想要累积多个值的其他任务):

let futureOfStrings: EventLoopFuture<[String]> =
    EventLoopFuture<String>.reduce(into: Array<String>(),
                                   futures: myArrayFutureStrings,
                                   on: someEventLoop,
                                   { array, nextValue in array.append(nextValue) })   

要专门[EventLoopFuture<Something>]变成EventLoopFuture<[Something]>你也可以使用较短的whenAllSucceed

let futureOfStrings: EventLoopFuture<[String]> =
    EventLoopFuture<String>.whenAllSucceed(myStringFutures, on: someEventLoop)
于 2020-06-05T10:35:26.747 回答
3

flatten像这样等待数组中的所有期货是可能的

[future1, future2, future3, future4].flatten(on: eventLoop)

因为flatten每个未来都应该回归Voidflatten它自己也会回归EventLoopFuture<Void>

有时我们需要处理一些具有简单值的数组,并使用返回的某种方法对每个值做一些事情,EventLoopFuture在这种情况下,代码可能如下所示

let array = ["New York", "Los Angeles", "Las Vegas"]

array.map { city in
     someOtherMethod(city).transform(to: ())
}.flatten(on: eventLoop)

在上面的示例中,方法someOtherMethod可以返回任何东西,但我们可以将其转换EventLoopFuture<Void>为使用 withflatten

于 2020-06-05T10:33:05.440 回答