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



使用此方法

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

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

最新更新