我有一组值映射到多个 Promise,每个 Promise 都给我一个 EventLoopFuture。所以我最终得到了一个具有可变大小 [EventLoopFuture] 的方法,并且我需要所有响应都成功才能继续。如果其中一个或多个返回错误,我需要执行错误场景。
在继续使用成功路径或错误路径之前,如何等待整个 [EventLoopFuture] 完成?
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)
flatten
像这样等待数组中的所有期货是可能的
[future1, future2, future3, future4].flatten(on: eventLoop)
因为flatten
每个未来都应该回归Void
,flatten
它自己也会回归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