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]]
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]]
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 Future
s,那么我想您不需要 pass ,但是使用andExecutionContext
的一般想法仍然可以工作。foldLeft
flatMap
如果给定一个 Seq[Future[T]] 您可以将其转换为 Future[Seq[T]] ,如下所示:
Val a: Seq[Future[T]] = ???
val resut: Future[Seq[T]] = Future.sequence(a)
比上面的样板少一点:)
我相信这应该这样做:
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
,或者停止失败 - 应该很容易做到。