1

By executing the code below, I was expecting to have "passed" printed right away on console and then, 3 seconds later, postman's server delayed response ({"delay":"3"}), but instead I'm having to wait 3 seconds to see "passed" printed, after the server response. What am I doing wrong?

    HttpClient client = HttpClient.newHttpClient();
       HttpRequest request = HttpRequest.newBuilder()
             .uri(URI.create("https://postman-echo.com/delay/3"))
             .header("cache-control", "no-cache")
             .header("postman-token", "6bac0475-7cd1-f51a-945f-2eb772483c2c")
             .build();
       client.sendAsync(request, BodyHandlers.ofString())
             .thenApply(HttpResponse::body)
             .thenAccept(System.out::println)
             .join(); 

       System.out.println("passed");
4
  • 1
    join() sounds like it waits for completion. Commented Feb 26, 2020 at 11:28
  • @Thilo by doing so doesn't it defeat the whole async idea? Commented Feb 26, 2020 at 11:31
  • Yes. So why do you join() ? Commented Feb 26, 2020 at 11:32
  • If you want to print before the request completes, do the println before you call join. Commented Feb 26, 2020 at 11:33

1 Answer 1

2

Thank to @Thilo's hints, I got the behavior I was looking for. What I had in mind before was something more like javascript, where you chain up your fluent calls and move ahead. In Java, you trigger the calls and later on, when you're ready to block, you call get() or join(). So, it became like that:

    HttpClient client = HttpClient.newHttpClient();
       HttpRequest request = HttpRequest.newBuilder()
             .uri(URI.create("https://postman-echo.com/delay/3"))
             .header("cache-control", "no-cache")
             .header("postman-token", "6bac0475-7cd1-f51a-945f-2eb772483c2c")
             .build();

       CompletableFuture cf = client.sendAsync(request, BodyHandlers.ofString())
             .thenApply(HttpResponse::body)
             .thenAccept(System.out::println); 

       System.out.println("passed");

       HttpResponse<String> result = (HttpResponse<String>)cf.join();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.