问题
I have funtion which is calling computeParallel() function which is calling 3 Futures F1,F2,F3 and returning String as return type.
def computeParallel():String =
{
val f1 = Future { "ss" }
val f2 = Future { "sss" }
val f3 = Future { "ssss" }
val result: Future[String] = for {
r1 <- f1
r2 <- f2
r3 <- f3
} yield (r1 + r2 + r3)
Await.result(result,scala.concurrent.duration.Duration.Inf)
}
Using Await to collect the Aggregated Results.But People are saying usage of Await is Bad way of coding.
So i have used below one.Which is returning the Unit type.
result.onComplete {
case Success(res) => return res
}
So if return Unit i cannot print anything.
can any help us.Is there anyother way to solve the problem
Thanks in Advance
回答1:
If computeParallel
must return String
you have to Await.result
.
"Good way of coding" is to work with futures as soon as you get into them.
def computeParallel(): Future[String] = {
val f1 = Future { "ss" }
val f2 = Future { "sss" }
val f3 = Future { "ssss" }
for {
r1 <- f1
r2 <- f2
r3 <- f3
} yield (r1 + r2 + r3)
}
computeParallel().map(result => ???)
return
normally shouldn't be used in Scala.
onComplete
won't help because it
runs on some arbitrary (unspecified) thread ...
and we don't block until it completes.
Difference between Await.result and futures.onComplete in Scala
Promise can be completed to future so again you'll have Future[String]
rather than String
.
来源:https://stackoverflow.com/questions/57990176/computation-with-futures-avoiding-await-method