Promises are used when you perform an operation that is expensive and relatively time consuming. For example, if you make an intensive query in a database, you do not want your end user to wait while you collect all the records.
In such cases, you return a promise instead of a result. This will stop the external interface from freezing, waiting for a response for intensive computing. It will get a real result after the calculation is complete.
Promises run in a separate thread, so use them only when necessary. In most cases, you just need to use the result.
Play has a nice page! Framework documentation that talks about asynchronous HTTP programming :
A promise will ultimately be redeemed with a value of type Result. Using Promise instead of the usual result, we can quickly return from our action without blocking anything. Then the game will serve the result as soon as the promise is paid.
If you need to transfer data, I will also consider EventSource (for events sent by the server) or WebSockets. I would also recommend watching the latest version of Play (2.3) and getting Java 8 to use Lambda Expressions, which will reduce the verbosity of the code. You can find some examples in here .
Oh, and it looks like you are abusing Promises. . You only need them if you are doing expensive computing and computing resources. Again, if your code looks unreadable due to anonymous inner classes and functions, I highly recommend switching to Java 8 and using lambda expressions .
Melvin sowah
source share