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

My PlayFramework Action returns before a Future is ready, how do I update a web page component?

我有一个调用 MongoDB 并获得 Future[Seq[Document]] 结果的 Scala PlayFramework 函数。在地图 zoom/pan 事件之后,通过 xhttp/GET 从网页上的 JavaScript 调用此播放 Action 函数。在执行 Future 的 onComplete/Success 之前,Play 端的我的 Action 方法 returns。所以我正在寻找一种方法来调用 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

getFutureOne 是临时的,它只是做一个 db.collection.find().first().toFuture。我只是想确保我与 MongoDB 的连接正常,确实如此。实际上,我会将其替换为对 return 位于边界框内的数据的查询。

Action 不适用于期货。使用 Action.async,这将 "wait"(技术上不是等待,而是安排)未来完成:

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"))
}

看看这个以供参考: https://www.playframework.com/documentation/2.4.x/ScalaAsync