簡體   English   中英

我的PlayFramework Action在Future准備就緒之前返回,如何更新網頁組件?

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

我有一個Scala PlayFramework函數,該函數調用MongoDB並獲取Future[Seq[Document]]結果。 在地圖縮放/平移事件之后,該播放Action功能是通過xhttp / GET從網頁上的JavaScript調用的。 在執行Future的onComplete/Success之前,Play端的My Action方法將返回。 因此,我正在尋找一種在Scala Future的onComplete / Success觸發時調用JavaScript函數以獲取數據的方法。 我該怎么做,還是我看錯了?

這是有問題的代碼。

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的連接正常工作。 實際上,我將其替換為查詢以返回落入邊界框內的數據。

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

請看一下以供參考: https : //www.playframework.com/documentation/2.4.x/ScalaAsync

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM