检查Future [Boolean]的结果为true还是false

时间:2016-02-01 21:14:55

标签: scala asynchronous playframework future

我有一个以下函数,它接收Future[List[BSONDocument]]并尝试返回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
    }

  }

2 个答案:

答案 0 :(得分:2)

result的类型为Future[Boolean](而不是Boolean)。

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

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

答案 1 :(得分:1)

正如其他人所指出的那样,一种方法是异步,如下所示:

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秒;如果未来在那段时间内成功完成,它将返回该值,否则将抛出异常。然后你可以像任何其他布尔值一样使用该值。

相关问题