Kooky_Lukey
Kooky_Lukey

Reputation: 137

Waiting for Future to be Complete in HTTP GET

I am trying to return a temperature conversion as a HTTP GET request and display it. Currently I do not think it is waiting for the future to complete. If I try and add the onComplete callback then it won't compile and complains about the async being overloaded.

def getTemperature = Action.async {
    val futureTemp = scala.concurrent.Future { convert.convertTemperature(convert.qTemperature.front) }
    futureTemp.map(i => Ok("Got result: " + i.value))
  }

def convertTemperature(cTemp:Temperature) : Future[Double] = Future {
    //If typeOfTemp is F convert it to C and vise versa
    val typeOfTemp = cTemp.typeOfTemp
    val tempVal = cTemp.tempVal

    typeOfTemp match {
      case "F" => (tempVal - 32) * 5 / 9
      case "C" => (tempVal / 5) + 32
    }
  }

If I return just i then it will show Future(<not completed>) If I return the i.value like in the code above it will show None I want it to wait and show the number value. I.e. F, 32 will just return 0

Upvotes: 0

Views: 59

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Action.async expects a function that returns Future[Result] however you are providing Future[Future[Result]] in the following line

Future { convert.convertTemperature(convert.qTemperature.front) }

because convertTemperature already returns Future. Try simplifying to

def getTemperature = Action.async {
  convert
    .convertTemperature(convert.qTemperature.front)
    .map(i => Ok(s"Got result: $i"))
}

Upvotes: 1

Related Questions