顺序执行任意数量的 Scala Futures 列表

Sequential execution of a list of an arbitrary number of Scala Futures

我阅读了 Scala Futures and Promises

我知道我可以使用回调、flatMap 组合器或 for-comprehension 来链接期货。当一个未来完成时,另一个未来开始等等。

有没有办法链接执行任意数量的期货,存储在 Scala 集合中(例如 List)? 我试图在这个期货列表上调用 Future.sequence 但它们一起开始并且它们是同时执行的(不是顺序的)。

def chainFutures(list: List[() => Future[Any]]): Future[Any] = {
  list match {
    case x :: Nil => Future.successful(x)
    case (x :: xs) => x() flatMap (_ => chainFutures(xs))
  }
}

如果您可以接受提供 return Future 的函数列表,这应该可以满足您的需求。 List[Future[_]] 的问题是,它们已经启动,所以它们不能在执行方面被链接起来。除了你提供一个线程 ExecutionContext.

如果失败,它return是第一个失败并停止执行其他期货。

我的回答更关心如何处理任意数量的列表 Scala Futures 函数.

  type FUTURE_FUNCTION = String => Future[String]

  def compose(fs: List[FUTURE_FUNCTION]): FUTURE_FUNCTION = fs match {
    case List(head) => head
    case head :: tail => head(_).flatMap { u => compose(tail)(u) }
  }

在上面的代码片段中,创建一个 compose 方法具有高阶 Future 函数参数。并且此方法迭代所有高阶函数并组成一个全新的 Future 函数。

使用示例:

  val f1: String => Future[String] =
    (s: String) => Future {
      s.toUpperCase
    }


  val f2: String => Future[String] =
    (s: String) => Future {
      s + " Hello World"
    }

  compose(List(f1, f2))("foo bar")
  > FOO BAR Hello World