1

I have a problem with the following code snippet

val prerequisiteFuture = processStepPrerequisitesDTO.getProcessStepPrerequisiteProcessTemplateIds(step.id.get)
prerequisiteFuture.map(prereqTemplates => {
  processTemplateDTO.getProcessTemplates(prereqTemplates).map(pres => {
    step.stepPrerequisites = Some(pres)
    step.prerequisites = processStepPrerequisitesDTO.getProcessStepPrerequisitesByProcessTemplateId(step.id.get).map(preReqs => {
      preReqs
    })
    step
  })
})

Problem is the following: enter image description here

found : scala.concurrent.Future[Seq[models.ProcessStepPrerequisitesModel]]* [error] required: Option[Seq[models.ProcessStepPrerequisitesModel]]

How Can I remove the Future? Thanks

Felix
  • 5,452
  • 12
  • 68
  • 163

3 Answers3

5

There is no way to get rid of Future unless you wait for the future to complete finally down the processing pipeline.

Transform the Future using map and flatMap or for-comprehension.

Let's say you have def foo: Future[A] and you want B

Transform the future

foo.map(toB)

Now you will get Future[B]. But there is no way to get B value without future completing the execution.

Without awaiting, the only way to get rid of Future is to wait for it to complete but return type will be Unit.

futureComputation.onComplete {
  case Success(_) =>
  case Failure(_) =>
}

Not good practice

import scala.concurrrent.duration._

Try(Await.result(prerequisiteFuture, 10.seconds)).toOption

More info: How risky is it to call Await.result on db calls

Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
2

You cannot just remove Future because Future abstracts the value that is probably not yet calculated. As I can see from your code you're trying to initialize mutable fields of step by mapping futures. This is definitely wrong.

Try to use for comprehension for this:

val combinedFuture = for {
  v1 <- methodReturningFuture1
  v2 <- methodReturningFuture2
  v3 <- methodReturningFuture3
} yield (v1,v2,v3)
Nyavro
  • 8,806
  • 2
  • 26
  • 33
0

I have a working solution now:

   val prerequisiteFuture = processStepPrerequisitesDTO.getProcessStepPrerequisiteProcessTemplateIds(step.id.get)
            prerequisiteFuture.map(prereqTemplates => {
              processTemplateDTO.getProcessTemplates(prereqTemplates).map(pres => {
                step.stepPrerequisites = Some(pres)

                processStepPrerequisitesDTO.getProcessStepPrerequisitesByProcessTemplateId(step.id.get).map(b =>
                  step.prerequisites = Some(b))

                step
              })
            })
DevBot
  • 427
  • 1
  • 7
  • 31
Felix
  • 5,452
  • 12
  • 68
  • 163