1
我正在使用reactivemongo驅動程序(使用Scala)編寫Play 2.3.2應用程序。 我寫了一個方法,在我的數據庫中搜索最常用的標籤,並更新max和tagFound變量。等待Scala應用程序中的異步調用終止
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]) =>...
完成之前執行該方法的最後一個語句?怎麼了?
謝謝,現在:使用
Action.async
爲docs描述,這樣你就可以直接返回Future(Ok(jsonObject))
但更好的辦法有用。 – 2014-10-06 12:30:21