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]]
答案 0 :(得分:4)
您可以将所有期货合并为一个foldLeft
和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 Future
,那么我猜您不会需要通过ExecutionContext
,但foldLeft
和flatMap
的一般想法应该是还在工作。
答案 1 :(得分:2)
如果给定Seq [Future [T]],你可以将它转换为Future [Seq [T]],如下所示:
Val a: Seq[Future[T]] = ???
val resut: Future[Seq[T]] = Future.sequence(a)
比以上更少的样板:)
答案 2 :(得分: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
以下,或者在失败时停止 - 应该很容易做到。