返回包含预期完成的嵌套未来的 Future[Unit] 的方法

Method returning Future[Unit] containing nested future that is expected to complete

用这个方法

def taskA(): Future[Unit] = Future {
Future {
  print("Starting nested future")
  Thread.sleep(3000)
  print("Finished nested future")
} 
print("starting outer future")
Thread.sleep(1000)
print("finished outer future")
}

是否可以在实际完成外部未来之前等待嵌套未来完成? 这就是我执行这个程序的方式:

print("Starting program")
val futureA = taskA()

futureA onComplete{
case Success(_) => print("future suceeded")
case Failure(_) => print("not able to execute future")
}

Await.result(futureA, Duration.Inf)

这是我的控制台输出:

15:18:52.357 [main] Starting program
15:18:52.563 [scala-execution-context-global-13] Starting nested future
15:18:52.564 [scala-execution-context-global-12] starting outer future
15:18:53.564 [scala-execution-context-global-12] finished outer future
15:18:53.566 [scala-execution-context-global-12] future suceeded

Process finished with exit code 0

如果你想做something然后somethingElse,那么你是在顺序执行两个操作,其中第二个操作必须等到第一个操作完成。出于所有实际目的,这正是 monadic flatMap 所做的。所以,你应该做这样的事情:

def taskA(): Future[Unit] = for {
  _ <- Future {
    print("Starting first future")
    Thread.sleep(3000)
    print("Finished first future")
  };
  _ <- Future {
    print("starting outer future")
    Thread.sleep(1000)
    print("finished outer future")
  }
} yield ()

第一个 _ <- ... 将确保第一个 future 在第二个 future 开始之前终止。