I develop a little server in PlayFramework2/Scala which has to retrieve data from multiple WS (REST/JSON), manipulate the data from theses WS, then compose and return a result.
I know how to call one WS, manipulate the data and return an Async response. But I don't know how how to call successively several web-services, handle the data between every call and generate an aggregated answer.
Exemple :
- Fetch the list of my prefered songs from WebService A
- then, for each song, fetch the artist detail from WS B (one call by song)
- then, generate and return something (aggregated list for example) using the A and B responses
- then, return the result
I am blocked by the asynchronous processings of WS API (WS.url(url).get => Promise[Response]
). Do I have to lean on Akka to solve this problem?
Thank you.
flatMap
andmap
are your friends! These two methods of thePromise
type allow to transform the result of aPromise[A]
into anotherPromise[B]
.Here is a simple example of them in action (I intentionally wrote explicitly more type annotations than needed, just to help to understand where transformations happen):
Without the unnecessary type annotations and using the “for comprehension” notation, you can write the following more expressive code: