调用一个 returns 未来 n 次的方法

Call a method that returns future n times

我想调用一个方法n次。仅当前一个调用成功时,才应进行每个后续调用。这种方法 return 是一个未来。我尝试的代码看起来像这样

    def doSomething: Future[R] = Future {
              //some logic 
              ???
    }

    def outer() = {
      val range = { 1 to 5 }

      def inner(range: Seq[Int]): Future[R]= 
        range.headOption match {
          case Some(head) =>
            doSomething.flatMap { _ => inner(range.tail)} 
          case None => ???
        }
      inner(range)
    }

如果 None,我想 return 最后一个未来的值 运行。如何做到这一点?

是这样的吗?

// assumes that implicit ExecutionContext is available
// if it isn't available here add it to signature
def callMeNTimes[T](n: Int)(future: => Future[T]): Future[T] =
  if (n <= 0) Future.failed(new Exception("Cannot run future less that 1 times"))
  else if (n == 1) future
  else future.flatMap(_ => callMeNTimes(n-1)(future))

callMeNTimes(5)(doSomething)

如果您需要汇总运行结果,您可以执行以下操作:

def repeat[A](n: Int, init: A)(future: A => Future[A]): Future[A] =
  if (n <= 0) Future.successful(init)
  else future(init).flatMap(a => repeat(n-1, a)(future))