1

I have a sequence of functions that return a future. I want to execute them sequentially i.e. after the first function future is complete, execute the next function and so on. Is there a way to do it?

ops: Seq[() => Future[Unit]]

4

3 回答 3

4

foldLeft您可以使用 a和将所有期货组合成一个期货flatMap

def executeSequentially(ops: Seq[() => Future[Unit]])(
  implicit exec: ExecutionContext
): Future[Unit] =
  ops.foldLeft(Future.successful(()))((cur, next) => cur.flatMap(_ => next()))

foldLeft确保从左到右的顺序并flatMap给出顺序执行。函数是用 执行的ExecutionContext,所以调用executeSequentially不是阻塞的。并且您可以在需要时添加回调或等待结果Future

如果您使用的是 Twitter Futures,那么我想您不需要 pass ,但是使用andExecutionContext的一般想法仍然可以工作。foldLeftflatMap

于 2016-03-04T18:52:22.483 回答
2

如果给定一个 Seq[Future[T]] 您可以将其转换为 Future[Seq[T]] ,如下所示:

Val a: Seq[Future[T]] = ???

val resut: Future[Seq[T]] = Future.sequence(a)

比上面的样板少一点:)

于 2016-03-05T16:07:41.943 回答
0

我相信这应该这样做:

import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration

def runSequentially(ops: Seq[() => Future[Unit]]): Unit = {
  ops.foreach(f => Await.result(f(), Duration.Inf))
}

如果您想少等待Duration.Inf,或者停止失败 - 应该很容易做到。

于 2016-03-04T18:34:51.627 回答