检查 Future[Boolean] 的结果是真还是假

Check result of Future[Boolean] to be either true or false

我有一个接收 Future[List[BSONDocument]] 并尝试 return 和 Boolean 的函数。我正在使用此函数来检查异步数据库调用返回的结果是否为空。

def checkExistingMessages(resultFromDB: Future[List[BSONDocument]]): Future[Boolean] = {

    resultFromDB.map { result =>
      if (result.isEmpty) {
        false
      }
      else true
    }

  }

然而,当我尝试做这样的事情时:

val result = checkExistingMessages(db.getDocument(name, age))
if (result){
    println("The result is TRUE")
}

我收到以下错误: Expression of type Future[Boolean] does not conform to expected type Boolean

更新 1:

def doesMsgExist(name: String, age: String): Boolean = {
    var result = false
    val msgExistsFlag = checkExistingMessages(db.getDocument(name, age))
    msgExistsFlag.foreach(isTrue => result = if(isTrue) false else true)
    result
  }


  def checkExistingMessages(resultFromDB: Future[List[BSONDocument]]): Future[Boolean] = {

    resultFromDB.map { list =>

      if (list.isEmpty) {
        false
      }
      else true
    }

  }

resultFuture[Boolean] 类型(而不是 Boolean)。

因此在您的情况下,您可以使用 foreach 访问 Future:

的结果
result.foreach(b => if(b) println("The result is TRUE"))

正如其他人所指出的,一种方法是异步执行此操作,方法如下:

val result: Future[Boolean] = checkExistingMessages(db.getDocument(name, age))
result.foreach(b => if(b) println("the result is true"))

或者,要同步处理计算,您可以执行以下操作将 Future[Boolean] 变成普通的 Boolean:

val result: Future[Boolean] = checkExistingMessages(db.getDocument(name, age))
val b: Boolean = Await.result(result, scala.concurrent.duration.Duration(5, "seconds"))

这将在等待 Future 完成时阻塞主线程最多 5 秒;如果未来在那个时候成功完成,它将 return 该值,否则将抛出异常。然后您可以像使用任何其他布尔值一样使用该值。