Reputation: 1695
I am trying to call 2 apis in a single method and I have to do a few calculations based on the responses I get.
This is so far what I have tried
def sortedRes() = Action.async {
ws.url(url).get().map { response =>
val value: JsValue = Json.parse(response.body)
val headVal = value.get.head
ws.url(sortUrl).get().map { response =>
val sorted: JsValue = Json.parse(response.body)
var sortedResult = sorted.get.head
}
println("----------------------")
println(headVal)
println(sortedResult)
Ok(Json.toJson(sortedResult)
}
}
I am getting an error on println(sortedResult)
line as it is not available there. How can I access sortedResult
there in scala.
Upvotes: 0
Views: 240
Reputation: 1789
Couple of things about your written code:
Use Flatmap on outer Future calls: You have asynchronous
action, every ws
call type should have the Future
type and therefore the outer map
should be flatMap
for avoiding dealing with Future[Future[...]]
.
Don't use var: The whole point of functional programming is immutability use val instead. If you can' think about your architecture/design and re implement the written function.
Move the action response to the body of Map: For more clean approach, why not move the Ok
response to the body of the second map?
Upvotes: 1
Reputation: 1651
As the ws.url(whatever).get()
is asynchronous, it will return a Future
that will contain your response, so it's not available in the moment you want to print it.
You have to flatMap
the outer Future
in order to manage the inner one, so then your sortedResult
will be available
I think this is what you want to do:
def sortedRes() = Action.async {
ws.url(url).get().flatMap { response =>
val value: JsValue = Json.parse(response.body)
val headVal = value.get.head
ws.url(sortUrl).get().map { response =>
val sorted: JsValue = Json.parse(response.body)
val sortedResult = sorted.get.head
println("----------------------")
println(headVal)
println(sortedResult)
Ok(Json.toJson(sortedResult)
}
}
}
Upvotes: 1