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