我的PlayFramework Action在Future准备好之前返回,如何更新网页组件?

gkn*_*uth 0 javascript scala future mongodb

我有一个Scala PlayFramework函数调用MongoDB并获得 Future[Seq[Document]]结果.在地图缩放/平移事件之后,Action通过xhttp/GET从网页上的JavaScript调用此Play 功能.Play侧的My Action方法在onComplete/Success执行Future之前返回.所以我正在寻找一种方法来调用JavaScript函数来获取Scala Future的onComplete/Success触发时的数据.我该怎么做,还是我看错了?

这是有问题的代码.

def rect(swLon: Float, swLat: Float, neLon: Float, neLat: Float) = Action {
  val sb = new StringBuilder()
  sb.append("<tt>boundingBox: swLon=" + swLon + ", swLat=" + swLat + ", neLon=" + neLon + ", neLat=" + neLat + "</tt>")
  if (oDb.isDefined) {
    val collection: MongoCollection[Document] = oDb.get.getCollection(collectionName)
    val fut = getFutureOne(collection) // returns a Future[Seq[Document]]
    fut onComplete {
      case Success(docs) => { for (doc <- docs) { setMongoJson(doc.toJson } }
      case Failure(t) => { println("FAIL: " + t.getMessage) }
    }
  }
  Ok(sb.toString)
}

// below is temporary until I figure out a better way to store/return the result when it comes in
private var mongoJson: String = ""
private def setMongoJson(s: String): Unit = mongoJson = s
Run Code Online (Sandbox Code Playgroud)

getFutureOne是暂时的,它只是一个db.collection.find().first().toFuture.我只是想确保我与MongoDB的连接正常工作,而且确实如此.实际上,我将用查询替换它以返回属于边界框的数据.

Alv*_*sco 5

Action不适合与期货合作.使用Action.async,将等待(技术上不等待,但安排)未来完成:

def rect(swLon: Float, swLat: Float, neLon: Float, neLat: Float) = Action.async {
  val sb = new StringBuilder()
  sb.append("<tt>boundingBox: swLon=" + swLon + ", swLat=" + swLat + ", neLon=" + neLon + ", neLat=" + neLat + "</tt>")
  if (oDb.isDefined) {
    val collection: MongoCollection[Document] = oDb.get.getCollection(collectionName)
    val fut = getFutureOne(collection) // returns a Future[Seq[Document]]
    fut.map {docs => 
      setMongoJson(doc.toJson)
      Ok(sb.toString)
    } recover {
      case e => BadRequest("FAIL: " + e.getMessage)
    }
  } else Future.successful(Ok("Not defined"))
}
Run Code Online (Sandbox Code Playgroud)

请查看此参考:https: //www.playframework.com/documentation/2.4.x/ScalaAsync