2014-10-06 7 views
1

나는 (Scala를 사용하여) reactivemongo 드라이버를 사용하여 Play 2.3.2 애플리케이션을 작성하고있다. db에서 가장 많이 사용 된 태그를 검색하고 max 및 tagFound 변수를 업데이트하는 메소드를 작성합니다.스칼라 애플리케이션에서 비동기 호출이 종료 될 때까지 기다린다

def max = Action { 
    var max: Int = 0 
    var tagFound: Tag = null 
    //obtain all the tags in the db. 
    val futureTags: Future[List[Tag]] = Tags.all.toList 
    futureTags map{ (tags: List[Tag]) => 
    tags map { (tag: Tag) => 
     //create the tag String 
     val tagName = tag.category + ":" + tag.attr 
     //search in the db the documents where tags.tag == tag. 
     val futureRequests : Future[List[recommendationsystem.models.Request]]= Requests.find(Json.obj("tags.tag" -> tagName)).toList 
     futureRequests map { (requests: List[recommendationsystem.models.Request]) => 
     //get the numbers of documents matching the tag 
     val number: Int= requests.size 
     if(number > max) { 
      max = number 
      tagFound = tag 
     } 
     println(max) 
     } 
    }       
} 

println("here max = " + max) 
//create the json result. 
val jsonObject = if(max > 0) Json.obj("tag" -> tagFound, "occurencies" -> max) else Json.obj("tag" -> "NoOne", "occurencies" -> 0) 
    Ok(jsonObject) 
} 

그러나 문제가이 println 메소드 명령에서 난 그게 futureTags map{ (tags: List[Tag]) =>... 문 앞에 println("here max = " + max)을 실행 볼 수 있습니다. 그래서 두 번째는 비동기 호출이라고 생각합니다. println 문에서 나는 첫 번째 인쇄 값이 here max = 0임을 알 수 있습니다. 그래서 어떻게하면 futureTags map{ (tags: List[Tag]) =>...이 완료되기 전에 완료 될 때까지 기다릴 수 있습니까? 뭐가 문제 야? 당신이 정말로 기다릴 필요가있는 경우

답변

2

, 당신은 사용할 수 있습니다 Away.result :

val result = Await.result(futureTags, 1 second) 

그러나 더 좋은 방법 docs에 설명 된대로 직접 Future(Ok(jsonObject))을 반환 할 수 있도록, Action.async을 사용하고 있습니다 :

def max = Action.async { 
    val futureTags: Future[List[Tag]] = Tags.all.toList 
    futureTags map{ tags => 
    ... 
    Ok(jsonObject) 
    } 
} 
+0

덕분에 지금, 그것은 작동합니다. –

관련 문제