asynchronous - Understanding Future in Scala -


I am writing Play 2.3.2 application in Scala. I use the responsive mongo driver to access a moddab database. I wrote the DB query to get the most used tags in the database. This method is an Action.async and it has been implemented as:

  max max = action.async {request = & gt; Var max: Int = 0 var tagFound: Get all tags in tag = zero / db. Val futureTags: future [list [tag]] = tag. All.to list future tags map {(Tags: list [tag]) => Tag map {(tags: tag) = & gt; // tag string wall tag name = tag.category + ":" + tag.attr // search in DB where tag tag tag == tag val futureRequest: future [list [recommendationsystem.models.Request]] = request again. (Json.obj ("tags.tag" -> tagname)) toList futureRequests map {(Request: list [recommendationssstem.models.Request]) = & gt; Get the number of documents matching the // tag val number: Int = requests.size if (number> maximum) {max = number tag} found = tag} println (max)}} val jsonObject = if (max > Json ("tag" -> gtfound, "occurencies" -> max) other Json.obj ("tag" -> no, "occurencies" -> 0) OK (JsonObject)}}   

But the behavior of this method is not deterministic, what is wrong ?? I do not understand

  val jsonObject = if (max> gt; 0) Json.obj ("tag" -> gtfound, "occurencies" -> gt; max) other jason Obj ("tag" -> "NoOne", "occurencies" -> 0) ok (jsonObject)}   

Asynchronous is executed and not waiting for tag Map statement ended

I have found some problems with your code:

  1. Users Do not, you do not know when they will be updated, so ethics really does not use verse at all.
  2. You use the map as foreach, that means you can not use any value Do not return, use it clearly in the future, if you do not return any value to the future then < / Li> Use Future [F] [T]] Flatemap to be used in the future [Future [T]] future [List [T]] future,
  3. Future To solve the result of

    Here is a rewritten piece of code, I have not compiled it, but you can get an idea of ​​how it should work :

      def max = Action.async {request = & gt; Tag.all.to list.flatemap {case tag = & gt; Val xs = Tag Map {case tag = & gt; Val tagname = tag Caribbean + ":" + tag. Remove (Jason.Obja ("tag tag" - tagname) toList.map (request => (tag, request.) Val f = future results (xs) f.map {case ys = & Valid = ys.foldLeft (option.empty [(Tag, Int)] {case ((maxTag, maxOcc), (tag, occ)) if> MaxOcc = & gt; (Some, _), _) = & gt; Case (none, (tag, opportunity)) => some (tag, opportunity)} val jsonObject = res.map {case (tag , MaxOcc)> & gt; Json.obj ("tag" -> tagfound, "occurencies" -> maxOcc)} getOrElse {Json.obj ("tag" -> "NoOne", "occurencies" - & gt; 0)} OK (jsonObject)}}}    

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -