期货回避计算方法 [英] Computation with Futures avoiding Await method
问题描述
我很高兴地调用了computeParallel()函数,该函数正在调用3 Futures F1,F2,F3并返回String作为返回类型.
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)
}
使用Await收集汇总结果.但是人们说使用Await是不好的编码方式.
Using Await to collect the Aggregated Results.But People are saying usage of Await is Bad way of coding.
所以我用的是下面的一种.这将返回Unit类型.
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
预先感谢
推荐答案
如果computeParallel
必须返回String
,则必须Await.result
.
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
通常不应在Scala中使用.
return
normally shouldn't be used in Scala.
onComplete
不能帮忙,因为它
在任意(未指定)线程上运行...
runs on some arbitrary (unspecified) thread ...
我们不会阻止它,直到它完成.
and we don't block until it completes.
承诺可以在将来完成,所以您将再次拥有Future[String]
而不是String
.
Promise can be completed to future so again you'll have Future[String]
rather than String
.
这篇关于期货回避计算方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!