在Action.async中运行多个Future

时间:2016-10-25 05:06:31

标签: scala playframework

我试过这种方式,但总是以Nil为例。

def findByLastName(lastName:String)=Action.async {
  val cursor = Json.obj("lastName" -> lastName)
  StudentDaoAndEntity.findAllStudent(cursor) flatMap { lastName =>
    ExaminationDao.findStudent(cursor) flatMap { lastName =>
      LibraryDao.findStudent(cursor) map {
        {
          case Nil => Ok("Student Not Found")
          case l: Seq[JsObject] => Ok(Json.toJson(l))
        }
      }
    }
  }
}

我在数据库中定义的函数是:

在StudentDaoAndEntity:

def findAllStudent(allStd: JsObject): Future[Seq[JsObject]] = {
  // gather all the JsObjects in a list
  collection.find(allStd).cursor[JsObject].collect[List]()
}

在LibraryDao中:

def findStudent(allStd: JsObject): Future[Seq[JsObject]] = {
  // gather all the JsObjects in a list
  collection.find(allStd).cursor[JsObject].collect[List]()
}

在ExamDao中:

def findStudent(allStd: JsObject): Future[Seq[JsObject]] = {
  // gather all the JsObjects in a list
  collection.find(allStd).cursor[JsObject].collect[List]()
}

2 个答案:

答案 0 :(得分:2)

问题在于隐藏每个lambda中的lastName参数(正如评论已经指出的那样)。话虽这么说,你可以使用for-understanding来使你的代码更具可读性

def findByLastName(lastName:String) = Action.async {
  val cursor = Json.obj("lastName" -> lastName)
  for {
    _ <- StudentDaoAndEntity.findAllStudent(cursor)
    _ <- ExaminationDao.findStudent(cursor)
    students <- LibraryDao.findStudent(cursor)
  } yield students match {
    case Nil => Ok("Student Not Found")
    case l: Seq[JsObject] => Ok(Json.toJson(l))
  }
}

答案 1 :(得分:1)

这就是我想要的:

def findByLastName(lastName:String)=Action.async {
  request =>

  val cursor = Json.obj("lastName" -> lastName)

  StudentDaoAndEntity.findAllStudent(cursor) flatMap {
    student =>

    ExaminationDao.findStudent(cursor) flatMap {
      examination =>

      LibraryDao.findStudent(cursor) map {
        {
          case Nil => Ok("Student Not Found")

          case library: Seq[JsObject] =>
            val finalResult = student ++ examination ++ library
            Ok(JsArray(finalResult))
        }
      }
    }
  }
}