玩连锁期货

时间:2016-01-25 04:28:52

标签: scala playframework

我正在为scala框架开发一些小网页 我使用mongodb

会员文件有meberinfo包含会员ID,出勤文件有

某人的出勤信息。

所以,我想先发现成员在某个群体中,之后

查找会员的出勤信息..

我的代码如下......

def attendanceBySubGroup(group: String, sub_group: String) = Action.async{

    var  obj : JsObject = Json.obj("group" -> group)
    if(sub_group ne "All"){
      obj = obj + ("sub_group" -> JsString(sub_group))
    }

    val cursor: Cursor[JsObject] = member_list.find(obj).cursor[JsObject]

    // gather all the JsObjects in a list
    val futureMemberList: Future[List[JsObject]] = cursor.collect[List]()




    val futurePersonsJsonArray: Future[JsArray] = futureMemberList.map {
      val m = ArrayBuffer.empty[JsObject]
      members => members.map{
        member => {
          val futureItem = attendance_list.find(Json.obj("member_id" -> member.\("_id").\("$oid"))).one[JsObject]
          futureItem.map {
            case Some(item) => member.+(("attendance" , item.\("attendance")))
            case None => member.++(Json.obj("attendance"-> false))
          }
        }
      }
      Json.arr(m.toList)
    }



    futurePersonsJsonArray.map {
      members =>
        Ok(members(0))
    }

但是,这不是我想要的工作

也许,futureItem.map {..是异步调用...

如何退回会员列表包括出勤信息..

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我不确定,这是最好的解决方案......

但它工作正常..

任何人都能找到更好的解决方案..请发布您的答案

  def attendanceBySubGroup(group: String, sub_group: String) = Action.async{

    var  obj : JsObject = Json.obj("group" -> group)
    if(sub_group ne "All"){
      obj = obj + ("sub_group" -> JsString(sub_group))
    }

    val cursor: Cursor[JsObject] = member_list.find(obj).cursor[JsObject]

    // gather all the JsObjects in a list
    val futureMemberList: Future[List[JsObject]] = cursor.collect[List]()

    val futureMemberListWithAttendance = futureMemberList.map {
      members =>  members.map{
        member => {
           val futureItem = attendance_list.find(Json.obj("member_id" -> member.\("_id").\("$oid"))).one[JsObject]
           futureItem.map[JsObject] {
            case Some(item) => member.+(("attendance" , item.\("attendance")))
            case None => member.++(Json.obj("attendance"-> false))
          }
        }
      }
    }

    futureMemberListWithAttendance.map{
     val memberAttendances = ArrayBuffer.empty[JsObject]
     aa => Await.result(Future.reduce(aa)((s1, s2) => {memberAttendances+=s1; s1 } ) , Duration.Inf)
     Ok(Json.arr(memberAttendances))
   }
  }