2

From play documentation

Whether the action code returns a Result or a Promise, both kinds of returned object are handled internally in the same way. There is a single kind of Action, which is asynchronous, and not two kinds (a synchronous one and an asynchronous one). Returning a Promise is a technique for writing non-blocking code.

does this mean that there is no difference/advantage or disadvantage in returning a Promise<Result> rather than returning a Result? If play! framework encloses calls to public static Result function() in a Promise, is there a point in the developer explicitly returning a Promise<Result>?

Can't Tell
  • 12,714
  • 9
  • 63
  • 91

1 Answers1

2

No, there is no point in explicitly returning a Promise<Result>, if what your code does is synchronous simply return a Result.

However, sometimes your code calls other code that returns a Promise because it performs a non-blocking asynchronous operation. In that case you should transform the promise to extract the information you need from it and then return it. By keeping it a Promise instead of unwrapping it - you're not forcing the thread to block and saving the overhead of a context switch which can be significant.

For example let's say you want to query a webservice:

WSRequestHolder holder = WS.url("someUrl");
Promise<JsonNode> json = holder.get();

Now, you can do the following:

JsonNode jsonResult = json.get(); // force the program to wait
return jsonResult; // return it

But this will force the thread to context-switch in a blocking io operation. Instead, you can return a promise directly:

return json; // return the promise

And save the overhead of context-switching, you can also use .map if you need to manipulate it first.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Benjamin, coming back to this question after some time, I have some more questions. I understand what you meant by `json.get();` will force the thread to context switch to a blocking I/O operation. But the I/O will have to happen eventually right? So some thread will block at some point of time? – Can't Tell Sep 11 '15 at 08:55
  • I/O can happen without a thread blocking - this is called (unsurprisingly) non-blocking IO and it happens through an event system. – Benjamin Gruenbaum Sep 11 '15 at 11:37
  • I have a similar question at http://stackoverflow.com/questions/32582411/how-to-convert-callback-to-a-promise. It would be great if you can lend a hand. – Can't Tell Sep 15 '15 at 09:28