【问题标题】:Getting all values for [EventLoopFuture] before proceeding在继续之前获取 [EventLoopF​​uture] 的所有值
【发布时间】:2020-09-24 12:28:09
【问题描述】:

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

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

【问题讨论】:

  • 非常感谢 imike 和 johannes-weiss 的精彩而详细的回答。不幸的是,SO没有办法将两个答案都标记为正确答案,否则我会有。

标签: swift promise future vapor swift-nio


【解决方案1】:

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

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

要专门将[EventLoopFuture&lt;Something&gt;] 转换为EventLoopFuture&lt;[Something]&gt;,您还可以使用较短的whenAllSucceed

let futureOfStrings: EventLoopFuture<[String]> =
    EventLoopFuture<String>.whenAllSucceed(myStringFutures, on: someEventLoop)

【讨论】:

    【解决方案2】:

    像这样使用flatten 可以等待数组中的所有期货

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

    对于flatten,每个未来都应返回Voidflatten 本身将返回EventLoopFuture&lt;Void&gt;

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

    let array = ["New York", "Los Angeles", "Las Vegas"]
    
    array.map { city in
         someOtherMethod(city).transform(to: ())
    }.flatten(on: eventLoop)
    

    在上面的示例中,someOtherMethod 方法可以返回任何东西,但我们可以将其转换为 EventLoopFuture&lt;Void&gt; 以与 flatten 一起使用

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2021-04-23
      • 1970-01-01
      • 2021-11-15
      • 2020-03-25
      • 2020-03-09
      • 2021-10-30
      • 2017-05-19
      • 2021-03-24
      相关资源
      最近更新 更多