MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Play Framework: Action reagiert, bevor ein Future fertig ist

Eine normale Action ist nicht für Futures ausgelegt. Verwenden Sie Action.async, das die Verarbeitung bis zum Abschluss des Futures plant:

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)

      fut.map { docs =>
        setMongoJson(doc.toJson)
        Ok(sb.toString)
      } recover {
        case e => BadRequest("FAIL: " + e.getMessage)
      }
    } else {
      Future.successful(Ok("Not defined"))
    }
  }

Wichtig ist, dass Ok(...) erst innerhalb von map erzeugt wird. Die Antwort wird somit erst gesendet, wenn das Datenbank-Future aufgelöst ist.