Computation with Futures avoiding Await method

☆樱花仙子☆ 提交于 2019-12-12 06:56:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!