Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...