我有以下代码片段,用于从数据库读取记录,并且为此使用 ReactiveMongo。
val futureList: Future[Option[BSONDocument]] = collection.find(query).cursor[BSONDocument].headOption
val os: Future[Option[Exam]] = futureList.map {
(list: Option[BSONDocument]) => list match {
case Some(examBSON) => {
val id = examBSON.getAs[Int]("id").get
val text = examBSON.getAs[String]("text").get
val description = examBSON.getAs[String]("description").get
val totalQuestions = examBSON.getAs[Int]("totalQuestions").get
val passingScore = examBSON.getAs[Int]("passingScore").get
Some(Exam(id, text, description, totalQuestions, passingScore))
}
case None => None
}
}.recover {
case t: Throwable => // Log exception
None
}
我不想更改我的方法签名以返回 Future。我想获取 Future 中的值并将其返回给调用者。
最佳答案
然后您需要使用可等待对象来阻止:
import scala.concurrent.duration._
val os: Future[Option[Exam]] = ???
val result = Await.result(os, 10 seconds)
result.getOrElse(/* some default */)
请注意,阻塞将阻塞线程,直到 future 完成或超时到期并引发异常,另请注意,这有点违背了异步计算的目的,但根据您的用例,它可能没问题。
如果您不需要立即获得结果,可以使用 onComplete
附加回调
os onComplete {
case Success(someOption) => myMethod(someOption)
case Failure(t) => println("Error)
}
请注意,仅当 future 完成时才会触发 onComplete
,因此结果无法立即访问,并且返回类型为 Unit
。
关于scala - 从 Scala 的 Future 中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898494/