I am struggling to understand how this code 'strips out' the Future.
getFutureResult()
returns a Future[String]
. So how come the return from the yield is only a String
?
def getFutureResult:Future[String] = { ... }
def getMyResult:String = {
for {
myFutureResult <- getFutureResult()
} yield {
myFutureResult
}
}
It is translated according to Scala
for
-comprehension translation rules:becomes:
This is a desugaring done by the compiler irregardless if
<expr>
has the type of a collection, a future or something else.Future
in Scala has a methodmap
, so it uses themyFutureResult
String
from above to construct anotherFuture[String]
.You never know if the resulting future
getMyResult
is completed -- you should install anonComplete
callback that will be called by the resulting future once it completes:The code for the
onComplete
method is executed asynchronously -- it might happen on a different thread, much later or simultaneously.If you really need to know if the
Future
has completed, use the:pattern to block the calling thread until the
getMyResult
future is completed. In general, you should avoid this and compose yourFuture
code usingfor
-comprehensions and callback.