playframework scala Seq[Future[Model]] removing th

2019-08-29 08:47发布

问题:

I have the following issue,

I have a Seq[Future[ProcessStepTemplatesModel]] and I want to remove the inner Future.

What I excpected to get is a Seq[ProcessStepTemplatesModel].

The complete code looks like this

Future.sequence {
        processSteps.map { step => // This is a "for each" over a Seq[ProcessStepTemplatesModel]
            val prerequisiteFuture = processStepPrerequisitesDTO.getProcessStepPrerequisiteProcessTemplateIds(step.id.get)

            prerequisiteFuture.map(prereqTemplates => {

             processTemplateDTO.getProessTemplatesForStepPreqrequsites(prereqTemplates).map(pres => {
                 step.stepPrerequisites ++Some(pres)
                 step
                })

            })
        }
      }

Thanks

UPDATE:

def getEditProcessTemplateData(processTemplateId: Int) = Action.async {
    //Get all steps of this process templates
    val stepIds: Future[Seq[Int]] = processTemplateDTO.getProcessStepTemplateIds(processTemplateId)

    val process = for {
      allApprovedProcessTemplates <- processTemplateDTO.getApprovedProcessTemplates //Get all approved process templates
      processTemplate <- processTemplateDTO.getProcessTemplate(processTemplateId) // Get the Process Template
      prerequisites <- getProcessTemplateForEdit(processPrerequisitesDTO.getProcessPrerequisiteProcessTemplateIdsByProcessTemplateId(processTemplateId))
      postConditions <- getProcessTemplateForEdit(processPostConditionsDTO.getProcessPostConditionProcessTemplateIdsByProcessTemplateId(processTemplateId))
      approvedProcessTemplate <- processTemplateDTO.getProcessTemplate(processTemplate.get.approveprocess)
      trainedProcessTemplate <- processTemplateDTO.getProcessTemplate(processTemplate.get.trainingsprocess)
      processSteps <- processTemplateDTO.getProcessStepTemplates(processTemplateId)
      // Step prerequisites
      processStepsPrerequisites <- getProcessStepsPrerequisites(stepIds)
      processStepsPrerequisiteProcessTemplate <- getProcessStepsPrerequisiteProcessTemplate(stepIds)
      processTemplatesForStepPrerequisites <- getProcessTemplateForStepPrerequisite(stepIds)
      // Step post conditions
      processStepsPostConditions <- getProcessStepsPostConditions(stepIds)
      processStepPostConditionProcessTemplate <- getProcessStepPostConditionProcessTemplate(stepIds)
      processTemplatesForStepPostConditions <- getProcessTemplateForStepPostCondition(stepIds)
      // Derived processes
      derivedProcesses <- getDerivedProcesses(stepIds)
      processTemplatesForStepDerivedProcesses <- getProcessStepsDerivedProcesses(stepIds)
      // Process to process step
      processStepsTemplates_ProcessTemplates <- getProcessStepsTemplates_ProcessTemplates(stepIds)
      processTemplatesForProcessTemplatesToProcessStep <- getProcessTemplateToProcessStepId(stepIds)
      responsible <- raciProcessTemplateDTO.getResponsibleProcessTemplates(processTemplateId) // get all responsibles for this process template
      accountable <- raciProcessTemplateDTO.getAccountableProcessTemplates(processTemplateId) // get all accountables for this process template
      consulted <- raciProcessTemplateDTO.getConsultedProcessTemplates(processTemplateId) // get all consulted for this process template
      informed <- raciProcessTemplateDTO.getInformedProcessTemplates(processTemplateId) // get all consulted for this process template
    } yield (allApprovedProcessTemplates, processTemplate, prerequisites, postConditions, processSteps, processStepsPrerequisites,
      processStepsPrerequisiteProcessTemplate, processTemplatesForStepPrerequisites, processStepsPostConditions, processStepPostConditionProcessTemplate, processTemplatesForStepPostConditions, derivedProcesses,
      processTemplatesForStepDerivedProcesses, processStepsTemplates_ProcessTemplates, processTemplatesForProcessTemplatesToProcessStep, approvedProcessTemplate, trainedProcessTemplate, responsible, accountable, consulted, informed)

    process.flatMap({ case (allApprovedProcessTemplates, processTemplate, prerequisites, postConditions, processSteps, processStepsPrerequisites,
    processStepsPrerequisiteProcessTemplate, processTemplatesForStepPrerequisites, processStepsPostConditions, processStepPostConditionProcessTemplate, processTemplatesForStepPostConditions, derivedProcesses,
    processTemplatesForStepDerivedProcesses, processStepsTemplates_ProcessTemplates, processTemplatesForProcessTemplatesToProcessStep, approvedProcessTemplate, trainedProcessTemplate, responsible, accountable, consulted, informed) =>

      Future.sequence {
        processSteps.map {
          step =>
            val prerequisiteFuture = processStepPrerequisitesDTO.getProcessStepPrerequisiteProcessTemplateIds(step.id.get)

            prerequisiteFuture.map(prereqTemplates => {

              processTemplateDTO.getProessTemplatesForStepPreqrequsites(prereqTemplates).map(pres => {
                  println("test", pres) // they are printed
                  step.stepPrerequisites ++Some(pres)
                  println("test2", step)
                 step
                })

            })
        }
      }.map {
        stepTemplates =>
          Ok(Json.obj(
            "allApprovedProcessTemplates" -> allApprovedProcessTemplates,
            "processTemplate" -> processTemplate,
            "prerequisites" -> prerequisites,
            "postConditions" -> postConditions,
            "approvedProcessTemplate" -> approvedProcessTemplate,
            "trainedProcessTemplate" -> trainedProcessTemplate,
            // Step prerequisites
            "processStepsPrerequisites" -> processStepsPrerequisites,
            "processStepsPrerequisiteProcessTemplate" -> processStepsPrerequisiteProcessTemplate,
            "processTemplatesForStepPrerequisites" -> processTemplatesForStepPrerequisites,
            // Step post conditions
            "processStepsPostConditions" -> processStepsPostConditions,
            "processStepPostConditionProcessTemplate" -> processStepPostConditionProcessTemplate,
            "processTemplatesForStepPostConditions" -> processTemplatesForStepPostConditions,
            // Derived processes
            "derivedProcesses" -> derivedProcesses,
            "processTemplatesForStepDerivedProcesses" -> processTemplatesForStepDerivedProcesses,
            // Process to process step
            "processStepsTemplates_ProcessTemplates" -> processStepsTemplates_ProcessTemplates,
            "processTemplatesForProcessTemplatesToProcessStep" -> processTemplatesForProcessTemplatesToProcessStep,
            "steps" -> "stepTemplates",
            "responsible" -> responsible,
            "accountable" -> accountable,
            "consulted" -> consulted,
            "informed" -> informed
          ))
      }
    })
  }

回答1:

Future.sequence transforms Seq[Future[ProcessStepTemplatesModel]] into Future[Seq[ProcessStepTemplatesModel]]. So if you need just Seq[ProcessStepTemplatesModel] you can wait till the future comes

Await.result({
  Future.sequence {
    processSteps.map ...
  }
}, 1 minute)

But whether blocking is a good idea in your situation only you can know.


For example here is a controller that having List[Future[Int]] and applying Future.sequence prints integers:

/app/controllers/HomeController.scala

package controllers

import javax.inject._

import play.api._
import play.api.mvc._

import scala.concurrent.Future

import scala.concurrent.ExecutionContext.Implicits.global

@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index() =
    Action.async {
      Future.sequence {
        List(Future(1), Future(2))
      }.map { nums =>
          Ok(views.html.index(nums))
      }
    }
}

/app/views/index.scala.html

@(nums: List[Int])

@main("Welcome to Play") {
  <h1>Welcome to Play!</h1>
    <ul>
    @for(num <- nums) {
        <li>@num</li>
    }
    </ul>
}

Ok, this one is more similar to yours and prints 11, 12:

  def index() =
    Action.async {
      Future.sequence {
        List(1, 2).map(num =>
          Future{
            Thread.sleep(5000)
            10
          }.map(n =>
            num + n
          )
        )
      }.map {
        nums =>
          Ok(views.html.index(nums))
      }
    }

Here

             step.stepPrerequisites ++Some(pres)
             step

I can't see how you use the value of step.stepPrerequisites ++Some(pres), you return the original step. Are there any side effects?



回答2:

working solution is:

Future.sequence {
        processSteps.map {
          step =>
            val prerequisiteFuture = processStepPrerequisitesDTO.getProcessStepPrerequisiteProcessTemplateIds(step.id.get)
            prerequisiteFuture.map(prereqTemplates => {
              processTemplateDTO.getProessTemplatesForStepPreqrequsites(prereqTemplates).map(pres => {
                  println("test", pres) // they are printed
                  step.stepPrerequisites = Some(pres)
                  println("test2", step)
                 step
                })
            })
        }
      }.flatMap {
        stepTemplates => {

          Future.sequence(stepTemplates).map(test =>

            Ok(Json.obj( [....]