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.Futurein Scala has a methodmap, so it uses themyFutureResultStringfrom above to construct anotherFuture[String].You never know if the resulting future
getMyResultis completed -- you should install anonCompletecallback that will be called by the resulting future once it completes:The code for the
onCompletemethod is executed asynchronously -- it might happen on a different thread, much later or simultaneously.If you really need to know if the
Futurehas completed, use the:pattern to block the calling thread until the
getMyResultfuture is completed. In general, you should avoid this and compose yourFuturecode usingfor-comprehensions and callback.