I am trying to find a more elegant way to execute 2 times a function which returns a Future[HttpReponse] and then to use the response of the 2-end call.
for {
// function post returns a Future[HttpResponse]
response <- post(uri, payload) // 1st
response <- post(uri, payload) // 2end
} yield {
// do something with the 2end response
}
This does not work:
for {
2 times response <- post(uri, payload)
} yield {
// response becomes of type Any instead of HttpResponse
}
If you need to make two sequential calls to a method that returns Future, you can use flatMap.
post(uri, payload).flatMap(_ => post(uri, payload))
This will not start the second post operation until the first one completes.
If you have multiple chained calls you can use foldLeft on a Range to apply this the appropriate number of times:
(0 to N-1).foldLeft(post(uri, payload)){
case (prev, _) => prev.flatMap(_ => post(uri, payload))
}
In practice you would probably use the value from the Range to track progress on this operation rather than discarding it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With