Get value from CompletionStage in java

I am using play2.5 with java 8. I am making a POST request to the server using

WSRequest request = ws.url("http://abababa .com"); WSRequest complexRequest = request.setHeader("X-API-Key", "xxxxxx") .setHeader("Content-Type", "application/x-www-form-urlencoded") CompletionStage<WSResponse> responsePromise = complexRequest.post("grant_type=password" + "&username=xxxxx&password=yyyyy"); CompletionStage<JsonNode> jsonPromise = responsePromise.thenApply(WSResponse::asJson); 

How to print the final answer answer. I want to return part of the answer to this function. Should the function calling this function have different code than synchronous code?

+7
java promise java-8
source share
3 answers

jsonPromise.toCompletableFuture().get()

+8
source share

The problem is that all this code runs asynchronously. If you really want to return from the method with the result, you will have to block until you get the result. Locking is not very good, as it affects performance. Usually you want to return the CompletionStage as it is and let the caller decide what to do with it. If, however, you need to fully return with the result, the code example below.

 WSRequest request = ws.url("http://abababa .com"); WSRequest complexRequest = request.setHeader("X-API-Key", "xxxxxx") .setHeader("Content-Type", "application/x-www-form-urlencoded") CompletionStage<WSResponse> responsePromise = complexRequest.post("grant_type=password" + "&username=xxxxx&password=yyyyy"); CompletionStage<JsonNode> jsonPromise = responsePromise.thenApply(WSResponse::asJson); Object waitGuard = new Object(); AtomicReference<JsonNode> resultReference = new AtomicReference(); synchronized(waitGuard){ jsonPromise.thenAccept( jsonNode -> { resultReference.set(jsonNode); waitGuard.notify(); }); waitGuard.wait(); } return resultReference.get(); 
+2
source share
 JsonNode jsonData = jsonPromise.toCompletableFuture().get() 

I tried the code above, but I get a compiler error to return JsonNode data, then I used

 JsonNode jsonData = jsonPromise.toCompletableFuture().join() 

and it works great

0
source share

All Articles