You can either:
- Await them (see here for demo):
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def returnsAFuture: Future[Int] = Future {
Thread.sleep(1000)
10
}
import scala.concurrent.Await
import scala.concurrent.duration._
println(Await.result(returnsAFuture, Duration.Inf))
- Sleep the thread for a specific period of time (see here for demo - based on the post you linked to):
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def returnsAFuture: Future[Int] = Future {
Thread.sleep(1000)
10
}
import scala.util.Success
returnsAFuture.onComplete {
case Success(value) => println(value)
case _ => println("No value found")
}
Thread.sleep(2000)
- Leave the Future alone and deal with it later by mapping inside it (see here for demo):
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def returnsAFuture: Future[Int] = Future {
Thread.sleep(1000)
10
}
val aNewFuture = returnsAFuture.map {_ * 2}
// do some other stuff
// access the result of the Future only when you absolutely have to
import scala.concurrent.Await
import scala.concurrent.duration._
println(Await.result(aNewFuture, Duration.Inf))
The whole point of a Future is that you can deal with it under the assumption that it will resolve successfully by leaving it as a Future for as long as you can and dealing with any exceptions thrown at the last possible moment.
If you are using a framework like Play, you can just return a Future at the end and Play will resolve it for you. If not though, you will need to wait for the Future to finish at some point.
I would recommend doing option 3 though, so you can leave this until the last moment and not block your Thread unnecessarily early.