简体   繁体   English

执行顺序返回未来的功能序列

[英]Executing sequence of functions that return a future sequentially

I have a sequence of functions that return a future. 我有一系列返回未来的函数。 I want to execute them sequentially ie 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]] 操作:Seq [()=> Future [Unit]]

You can combine all the futures into a single one with a foldLeft and flatMap : 您可以将所有期货与foldLeftflatMap合并为一个期货:

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

foldLeft ensures the order from left to right and flatMap gives sequential execution. foldLeft确保foldLeft的顺序, flatMap提供顺序执行。 Functions are executed with the ExecutionContext , so calling executeSequentially is not blocking. 函数是使用ExecutionContext ,因此调用executeSequentially不会阻塞。 And you can add callbacks or await on the resulting Future when/if you need it. 您可以添加回调或在需要时在生成的Future上等待。

If you are using Twitter Future s, then I guess you won't need to pass ExecutionContext , but the general idea with foldLeft and flatMap should still work. 如果您使用的是Twitter Future ,那么我想您不需要传递ExecutionContext ,但是foldLeftflatMap的基本思想仍然可以使用。

If given a Seq[Future[T]] you can convert it to a Future[Seq[T]] like so: 如果给定了Seq [Future [T]],则可以将其转换为Future [Seq [T]],如下所示:

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

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

a little less boilerplate than the above :) 样板比上述少:)

I believe this should do it: 我相信应该这样做:

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))
}

If you want to wait less then Duration.Inf , or stop at failure - should be easy to do. 如果您想减少等待Duration.Inf ,那么Duration.Inf或在失败时停止-应该很容易做到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM