2017-07-20 12 views
0

私は必要ではない約束をしています。 (JavaはWSを再生使用)Java sync promise(CompletionStageを使用)

public CompletionStage<Result> doSomething() { 
    JsonNode json = request().body().asJson(); 

    /* 
    * Promise not required. Just return BadRequest. 
    */ 
    if (json == null) { 
     // I think I am overkilling it here 
     ObjectNode result = Json.newObject(); 
     result.put("error", "some error"); 
     return CompletableFuture.supplyAsync(() -> {return 0;}) 
       .thenApply(i -> badRequest(result)); 
    } 

    /* 
    * Promise required. 
    */ 
    return ws.url("http://www.example.com/") 
      .get() 
      .thenApply(response -> { 
       String body = response.getBody(); 
       // Do something 
       return ok(body); 
      }); 
} 

ため、私は自分のコードの第2部分のリターンがCompletionStage<Result>する必要があります。

この単純なレスポンスのために、この非同期コードが本当に必要ですか?私のreturn 0は、構文エラーを起こさない限り、コードには役に立たない。

答えて

0

予想よりも簡単でした。 return 0実際のリターンコードに置き換えることができ、またthenApplyの繰り返しを避けることができるため、全く必要ありません。

if (json == null) { 
     return CompletableFuture.supplyAsync(() -> { 
      ObjectNode result = Json.newObject(); 
      result.put("error", "some error"); 
      return badRequest(result); 
     }); 
    } 

そしてまた、Java Play Result and CompletionStage<Result> are handled by the same way

ので、約束を必要としない部分がで置き換えることができます。

関連する問題