-3

I was wondering why the following function doesMsgExist() always returns false even when the results from the DB is not empty.

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
    }

  }
summerNight
  • 1,446
  • 3
  • 25
  • 52
  • 1
    I think this question has a too wide scope, please consider restricting the scope of the question, like leaving only the `checkExistingMessages` method and letting us know how it behaves with different input. – Dani Feb 02 '16 at 23:06
  • 1
    I don't see how it could have too wide a scope. Seems fairly straight forward what is being asked and to what the underlying issue is. – wheaties Feb 03 '16 at 21:33

1 Answers1

2

You are immediately returning the result but you are using a Future to evaluate it. That means that the object which represents the computation is being created but you have no guarantee when that computation will resolve. Hence, the value you return is false.

Think of a Future as a place holder for some action which will happen in the future. If you want to capture the actual result you should do something with a signature like this:

def doesMsgExist(name: String, age: Boolean): Future[Boolean] =

and have the evaluation returned with the Future. If not, you're going to have to surround it by an Await.

wheaties
  • 35,646
  • 15
  • 94
  • 131
  • Is there anything else other than setting a time limit? Why does it have to be so complex, all I want is to see the result of a DB operation. – summerNight Feb 02 '16 at 19:06
  • 2
    @summerNight it's "complex" being you've introduced multi-threading. There is no other way. – wheaties Feb 02 '16 at 19:09