我如何从未来获取布尔值[设置]

Mic*_*ova 1 dictionary scala filter

我有一个从 getProductSettingsMethod 返回的 Future [ProductSettings]。现在我需要 ClearCanLoad 字段中的 true 或 false

   def getEmployerProductSettingsQuery(employer: Employer): DBIOAction[ProductSettings, NoStream, Effect.Read] = {
val productSettingsQ = productSettingsQuery.filter(_.employerId === employer.id).result
productSettingsQ.map(_.headOrServerException(s"Could not find ProductSettings for employer ${employer.id}"))
 }

   def getEmployerProductSettings(employer: Employer): Future[ProductSettings] =
db.run(getEmployerProductSettingsQuery(employer))
Run Code Online (Sandbox Code Playgroud)

我尝试了 .map、filter、flatMap 等,但没有一个起作用

def cleared (employer : Employer) :Boolean = {
val f : Future[ProductSettings] = 
 getEmployerProductSettings(employer)

  val iscleared: Boolean = f.filter { x =>
    x.clearedCanLoadSpenditCards match {
      case true =>
        true
      case false =>
        false
    }
  }
Run Code Online (Sandbox Code Playgroud)

}

这不起作用,过滤器也不起作用

val f : Future[ProductSettings] = getEmployerProductSettings(employer)

     val iscleared  = f . 
  .filter(_.clearedCanLoadSpenditCards.equals(true)).equals(true)

case class ProductSettings(id: Long,
                       employerId: Long,
                       enableCard: Boolean,
                       enableLt: Boolean,
                       enableLtRefundDays: Boolean,
                       enableLtConversion: Boolean,
                       enableLtOPayment: Boolean,
                       clearedCanLoad: Boolean,
                       clearedAt:Option[LocalDateTime]) {
Run Code Online (Sandbox Code Playgroud)

equals true 应该返回布尔值,但我得到一个 Future[Boolean] 返回。我如何提取布尔值

sen*_*vic 5

主要目的Future是异步执行代码。阻止未来从中获取价值就违背了它的目的。但如果您确实需要该cleared方法返回,Boolean您可以阻止 future 直到它的值被解析。

您可以通过使用以下方法来实现此目的Await

import scala.concurrent.duration._

val result: ProductSettings = scala.concurrent.Await.result(f, 1 second)
Run Code Online (Sandbox Code Playgroud)

这个有待未来解决。如果一秒钟过去但f仍未解决,则会抛出TimeoutException

scala.concurrent.Await#结果

  • 而不是 `IllegalArgumentException`,它应该是 [`TimeoutException`](https://www.scala-lang.org/api/current/scala/concurrent/index.html#TimeoutException=java.util.concurrent.TimeoutException) 如果指定的“最多”等待时间已过。 (2认同)