How to save Vert.x WebClient result and return it in method












2















I have a method that is used in my Java Vert.x project which calls another service using WebClient. I want to save the result of that call in a JsonObject and return it. I'm assuming that I need to use futures for this, but when I run GetItemsService.retrieveItems, aside from my "print future below" message all I see in the console is Future{unresolved}.



How can I save the result from my GetItemsManager.getItems web client call in a variable?



public class GetItemsManager {
public Future<JsonObject> getItems(Future<JsonObject> future, Vertx vertx, RoutingContext routingContext) {
WebClient webClient = WebClient.create(vertx);
HttpServerResponse response = routingContext.response();
JsonObject data = new JsonObject();
response.setChunked(true);
response.putHeader("content-type", "text/plain");
response.putHeader("Access-Control-Allow-Origin", "*");
webClient.post(80, Constants.API_URL, "/items")
.as(BodyCodec.jsonArray())
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("ugws7", Constants.SERVICES_URL)
.sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
if (ar.succeeded()) {
HttpResponse<JsonArray> result = ar.result();
JsonArray body = result.body();
data.put("data", body.getJsonObject(0));
future.complete(data);
} else {
future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
}
});
return future;
}
}




public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GetItemsManager().getItems(future, vertx, routingContext);
String jsonObject = future.toString();
System.out.println("print future below");
System.out.println(jsonObject);
}
}


UPDATE



As per Peter's answer, I've tried to update my code with the following:



   public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GeItemsManager().getItems(future, vertx, routingContext);
String jsonObject;
Future<JsonObject> f = future.setHandler(handler -> {
handler.result();
});
System.out.println("Print future below");
System.out.println(f);
}
}


I still cannot assign the result of the call to a variable (f).










share|improve this question

























  • The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

    – taygetos
    Nov 21 '18 at 19:19











  • Got it. Thanks. How do I fix it to do what I am trying to get it to do?

    – aCarella
    Nov 21 '18 at 20:40











  • Why do you need to access the result outside of your handler block?

    – taygetos
    Nov 21 '18 at 21:32











  • I want to pass it to another method.

    – aCarella
    Nov 21 '18 at 21:58











  • Just call the other method inside the handler too.

    – taygetos
    Nov 21 '18 at 23:34
















2















I have a method that is used in my Java Vert.x project which calls another service using WebClient. I want to save the result of that call in a JsonObject and return it. I'm assuming that I need to use futures for this, but when I run GetItemsService.retrieveItems, aside from my "print future below" message all I see in the console is Future{unresolved}.



How can I save the result from my GetItemsManager.getItems web client call in a variable?



public class GetItemsManager {
public Future<JsonObject> getItems(Future<JsonObject> future, Vertx vertx, RoutingContext routingContext) {
WebClient webClient = WebClient.create(vertx);
HttpServerResponse response = routingContext.response();
JsonObject data = new JsonObject();
response.setChunked(true);
response.putHeader("content-type", "text/plain");
response.putHeader("Access-Control-Allow-Origin", "*");
webClient.post(80, Constants.API_URL, "/items")
.as(BodyCodec.jsonArray())
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("ugws7", Constants.SERVICES_URL)
.sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
if (ar.succeeded()) {
HttpResponse<JsonArray> result = ar.result();
JsonArray body = result.body();
data.put("data", body.getJsonObject(0));
future.complete(data);
} else {
future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
}
});
return future;
}
}




public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GetItemsManager().getItems(future, vertx, routingContext);
String jsonObject = future.toString();
System.out.println("print future below");
System.out.println(jsonObject);
}
}


UPDATE



As per Peter's answer, I've tried to update my code with the following:



   public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GeItemsManager().getItems(future, vertx, routingContext);
String jsonObject;
Future<JsonObject> f = future.setHandler(handler -> {
handler.result();
});
System.out.println("Print future below");
System.out.println(f);
}
}


I still cannot assign the result of the call to a variable (f).










share|improve this question

























  • The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

    – taygetos
    Nov 21 '18 at 19:19











  • Got it. Thanks. How do I fix it to do what I am trying to get it to do?

    – aCarella
    Nov 21 '18 at 20:40











  • Why do you need to access the result outside of your handler block?

    – taygetos
    Nov 21 '18 at 21:32











  • I want to pass it to another method.

    – aCarella
    Nov 21 '18 at 21:58











  • Just call the other method inside the handler too.

    – taygetos
    Nov 21 '18 at 23:34














2












2








2








I have a method that is used in my Java Vert.x project which calls another service using WebClient. I want to save the result of that call in a JsonObject and return it. I'm assuming that I need to use futures for this, but when I run GetItemsService.retrieveItems, aside from my "print future below" message all I see in the console is Future{unresolved}.



How can I save the result from my GetItemsManager.getItems web client call in a variable?



public class GetItemsManager {
public Future<JsonObject> getItems(Future<JsonObject> future, Vertx vertx, RoutingContext routingContext) {
WebClient webClient = WebClient.create(vertx);
HttpServerResponse response = routingContext.response();
JsonObject data = new JsonObject();
response.setChunked(true);
response.putHeader("content-type", "text/plain");
response.putHeader("Access-Control-Allow-Origin", "*");
webClient.post(80, Constants.API_URL, "/items")
.as(BodyCodec.jsonArray())
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("ugws7", Constants.SERVICES_URL)
.sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
if (ar.succeeded()) {
HttpResponse<JsonArray> result = ar.result();
JsonArray body = result.body();
data.put("data", body.getJsonObject(0));
future.complete(data);
} else {
future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
}
});
return future;
}
}




public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GetItemsManager().getItems(future, vertx, routingContext);
String jsonObject = future.toString();
System.out.println("print future below");
System.out.println(jsonObject);
}
}


UPDATE



As per Peter's answer, I've tried to update my code with the following:



   public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GeItemsManager().getItems(future, vertx, routingContext);
String jsonObject;
Future<JsonObject> f = future.setHandler(handler -> {
handler.result();
});
System.out.println("Print future below");
System.out.println(f);
}
}


I still cannot assign the result of the call to a variable (f).










share|improve this question
















I have a method that is used in my Java Vert.x project which calls another service using WebClient. I want to save the result of that call in a JsonObject and return it. I'm assuming that I need to use futures for this, but when I run GetItemsService.retrieveItems, aside from my "print future below" message all I see in the console is Future{unresolved}.



How can I save the result from my GetItemsManager.getItems web client call in a variable?



public class GetItemsManager {
public Future<JsonObject> getItems(Future<JsonObject> future, Vertx vertx, RoutingContext routingContext) {
WebClient webClient = WebClient.create(vertx);
HttpServerResponse response = routingContext.response();
JsonObject data = new JsonObject();
response.setChunked(true);
response.putHeader("content-type", "text/plain");
response.putHeader("Access-Control-Allow-Origin", "*");
webClient.post(80, Constants.API_URL, "/items")
.as(BodyCodec.jsonArray())
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("ugws7", Constants.SERVICES_URL)
.sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
if (ar.succeeded()) {
HttpResponse<JsonArray> result = ar.result();
JsonArray body = result.body();
data.put("data", body.getJsonObject(0));
future.complete(data);
} else {
future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
}
});
return future;
}
}




public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GetItemsManager().getItems(future, vertx, routingContext);
String jsonObject = future.toString();
System.out.println("print future below");
System.out.println(jsonObject);
}
}


UPDATE



As per Peter's answer, I've tried to update my code with the following:



   public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
Future<JsonObject> future = Future.future();
new GeItemsManager().getItems(future, vertx, routingContext);
String jsonObject;
Future<JsonObject> f = future.setHandler(handler -> {
handler.result();
});
System.out.println("Print future below");
System.out.println(f);
}
}


I still cannot assign the result of the call to a variable (f).







java asynchronous client future vert.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 16:14







aCarella

















asked Nov 21 '18 at 15:15









aCarellaaCarella

88362549




88362549













  • The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

    – taygetos
    Nov 21 '18 at 19:19











  • Got it. Thanks. How do I fix it to do what I am trying to get it to do?

    – aCarella
    Nov 21 '18 at 20:40











  • Why do you need to access the result outside of your handler block?

    – taygetos
    Nov 21 '18 at 21:32











  • I want to pass it to another method.

    – aCarella
    Nov 21 '18 at 21:58











  • Just call the other method inside the handler too.

    – taygetos
    Nov 21 '18 at 23:34



















  • The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

    – taygetos
    Nov 21 '18 at 19:19











  • Got it. Thanks. How do I fix it to do what I am trying to get it to do?

    – aCarella
    Nov 21 '18 at 20:40











  • Why do you need to access the result outside of your handler block?

    – taygetos
    Nov 21 '18 at 21:32











  • I want to pass it to another method.

    – aCarella
    Nov 21 '18 at 21:58











  • Just call the other method inside the handler too.

    – taygetos
    Nov 21 '18 at 23:34

















The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

– taygetos
Nov 21 '18 at 19:19





The main problem with your code that you don't wait for your Future. You are accessing it before the handler is called. Therefore the result is missing.

– taygetos
Nov 21 '18 at 19:19













Got it. Thanks. How do I fix it to do what I am trying to get it to do?

– aCarella
Nov 21 '18 at 20:40





Got it. Thanks. How do I fix it to do what I am trying to get it to do?

– aCarella
Nov 21 '18 at 20:40













Why do you need to access the result outside of your handler block?

– taygetos
Nov 21 '18 at 21:32





Why do you need to access the result outside of your handler block?

– taygetos
Nov 21 '18 at 21:32













I want to pass it to another method.

– aCarella
Nov 21 '18 at 21:58





I want to pass it to another method.

– aCarella
Nov 21 '18 at 21:58













Just call the other method inside the handler too.

– taygetos
Nov 21 '18 at 23:34





Just call the other method inside the handler too.

– taygetos
Nov 21 '18 at 23:34












2 Answers
2






active

oldest

votes


















2














I hope this helps i tried to add useful comments to your code.



GetItemsManager



public class GetItemsManager {
public Future<JsonObject> getItems(Vertx vertx, RoutingContext routingContext) {
//Note1: you can create the future here, no need to pass as a parameter
Future<JsonObject> future = Future.future();
...
webClient.post(80, Constants.API_URL, "/items")
...
.sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
if (ar.succeeded()) {
...
future.complete(data);
} else {
future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
}
});
return future;
}
}


GetItemsService



public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
new GetLocationsManager().getItems(vertx, routingContext) // returns Future<JsonObject>
.setHandler(handler -> {
//Note2: this codeblock is executed when your future is completed (or failed)
if(handler.succeeded()){
//Note3: handler.result() contains the result from the getItems call (future.complete(data))
JsonObject items = handler.result();
doSomethingWithTheItems(items);
String itemsEncodedToString = items.encode();
// serve the response
routingContext.response().end(itemsEncodedToString);
}else{
// serve error response
routingContext.response().end("something terrible happened" + handler.cause());
}
});
}

public void doSomethingWithTheItems(JsonObject items){
// do something here with your items
}
}


// Option 2 if you want to execute some other async method



public class GetItemsService {
public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
new GetLocationsManager().getItems(vertx, routingContext);
.compose(this::doSomethingAsyncWithTheItems)
.setHandler(handler -> {
if(handler.succeeded()){
//Note4: handler.result() contains the result from the doSomethingAsyncWithTheItems call (future.complete(...))
JsonObject didSomethingWithTheItems = handler.result();
routingContext.response().end(didSomethingWithTheItems.encode());
}else{
// serve error response
routingContext.response().end("something terrible happened");
}
});
}

public Future<JsonObject> doSomethingAsyncWithTheItems(JsonObject items){
Future<JsonObject> future = Future.future();
otherAsyncCallThatReturnsAFuture.setHandler(handler -> {
if(handler.succeeded()){
future.complete(...)
}else{
future.fail(...)
}
})
return future;
}
}





share|improve this answer































    3














    Try something like



    public class GetItemsService {
    public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
    Future<JsonObject> future = Future.future();
    new GetLocationsManager().getItems(future, vertx, routingContext);
    future.setHandler(h ->{
    routingContext.response().end(h.result().encode());
    });
    }
    }





    share|improve this answer
























    • Thanks for responding. How do I save the result in a variable, though?

      – aCarella
      Nov 21 '18 at 16:03











    • The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

      – taygetos
      Nov 21 '18 at 16:06











    • Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

      – aCarella
      Nov 21 '18 at 16:10






    • 1





      You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

      – taygetos
      Nov 21 '18 at 16:13






    • 1





      Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

      – taygetos
      Nov 21 '18 at 16:18











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415119%2fhow-to-save-vert-x-webclient-result-and-return-it-in-method%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    I hope this helps i tried to add useful comments to your code.



    GetItemsManager



    public class GetItemsManager {
    public Future<JsonObject> getItems(Vertx vertx, RoutingContext routingContext) {
    //Note1: you can create the future here, no need to pass as a parameter
    Future<JsonObject> future = Future.future();
    ...
    webClient.post(80, Constants.API_URL, "/items")
    ...
    .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
    if (ar.succeeded()) {
    ...
    future.complete(data);
    } else {
    future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
    }
    });
    return future;
    }
    }


    GetItemsService



    public class GetItemsService {
    public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
    new GetLocationsManager().getItems(vertx, routingContext) // returns Future<JsonObject>
    .setHandler(handler -> {
    //Note2: this codeblock is executed when your future is completed (or failed)
    if(handler.succeeded()){
    //Note3: handler.result() contains the result from the getItems call (future.complete(data))
    JsonObject items = handler.result();
    doSomethingWithTheItems(items);
    String itemsEncodedToString = items.encode();
    // serve the response
    routingContext.response().end(itemsEncodedToString);
    }else{
    // serve error response
    routingContext.response().end("something terrible happened" + handler.cause());
    }
    });
    }

    public void doSomethingWithTheItems(JsonObject items){
    // do something here with your items
    }
    }


    // Option 2 if you want to execute some other async method



    public class GetItemsService {
    public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
    new GetLocationsManager().getItems(vertx, routingContext);
    .compose(this::doSomethingAsyncWithTheItems)
    .setHandler(handler -> {
    if(handler.succeeded()){
    //Note4: handler.result() contains the result from the doSomethingAsyncWithTheItems call (future.complete(...))
    JsonObject didSomethingWithTheItems = handler.result();
    routingContext.response().end(didSomethingWithTheItems.encode());
    }else{
    // serve error response
    routingContext.response().end("something terrible happened");
    }
    });
    }

    public Future<JsonObject> doSomethingAsyncWithTheItems(JsonObject items){
    Future<JsonObject> future = Future.future();
    otherAsyncCallThatReturnsAFuture.setHandler(handler -> {
    if(handler.succeeded()){
    future.complete(...)
    }else{
    future.fail(...)
    }
    })
    return future;
    }
    }





    share|improve this answer




























      2














      I hope this helps i tried to add useful comments to your code.



      GetItemsManager



      public class GetItemsManager {
      public Future<JsonObject> getItems(Vertx vertx, RoutingContext routingContext) {
      //Note1: you can create the future here, no need to pass as a parameter
      Future<JsonObject> future = Future.future();
      ...
      webClient.post(80, Constants.API_URL, "/items")
      ...
      .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
      if (ar.succeeded()) {
      ...
      future.complete(data);
      } else {
      future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
      }
      });
      return future;
      }
      }


      GetItemsService



      public class GetItemsService {
      public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
      new GetLocationsManager().getItems(vertx, routingContext) // returns Future<JsonObject>
      .setHandler(handler -> {
      //Note2: this codeblock is executed when your future is completed (or failed)
      if(handler.succeeded()){
      //Note3: handler.result() contains the result from the getItems call (future.complete(data))
      JsonObject items = handler.result();
      doSomethingWithTheItems(items);
      String itemsEncodedToString = items.encode();
      // serve the response
      routingContext.response().end(itemsEncodedToString);
      }else{
      // serve error response
      routingContext.response().end("something terrible happened" + handler.cause());
      }
      });
      }

      public void doSomethingWithTheItems(JsonObject items){
      // do something here with your items
      }
      }


      // Option 2 if you want to execute some other async method



      public class GetItemsService {
      public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
      new GetLocationsManager().getItems(vertx, routingContext);
      .compose(this::doSomethingAsyncWithTheItems)
      .setHandler(handler -> {
      if(handler.succeeded()){
      //Note4: handler.result() contains the result from the doSomethingAsyncWithTheItems call (future.complete(...))
      JsonObject didSomethingWithTheItems = handler.result();
      routingContext.response().end(didSomethingWithTheItems.encode());
      }else{
      // serve error response
      routingContext.response().end("something terrible happened");
      }
      });
      }

      public Future<JsonObject> doSomethingAsyncWithTheItems(JsonObject items){
      Future<JsonObject> future = Future.future();
      otherAsyncCallThatReturnsAFuture.setHandler(handler -> {
      if(handler.succeeded()){
      future.complete(...)
      }else{
      future.fail(...)
      }
      })
      return future;
      }
      }





      share|improve this answer


























        2












        2








        2







        I hope this helps i tried to add useful comments to your code.



        GetItemsManager



        public class GetItemsManager {
        public Future<JsonObject> getItems(Vertx vertx, RoutingContext routingContext) {
        //Note1: you can create the future here, no need to pass as a parameter
        Future<JsonObject> future = Future.future();
        ...
        webClient.post(80, Constants.API_URL, "/items")
        ...
        .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
        if (ar.succeeded()) {
        ...
        future.complete(data);
        } else {
        future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
        }
        });
        return future;
        }
        }


        GetItemsService



        public class GetItemsService {
        public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
        new GetLocationsManager().getItems(vertx, routingContext) // returns Future<JsonObject>
        .setHandler(handler -> {
        //Note2: this codeblock is executed when your future is completed (or failed)
        if(handler.succeeded()){
        //Note3: handler.result() contains the result from the getItems call (future.complete(data))
        JsonObject items = handler.result();
        doSomethingWithTheItems(items);
        String itemsEncodedToString = items.encode();
        // serve the response
        routingContext.response().end(itemsEncodedToString);
        }else{
        // serve error response
        routingContext.response().end("something terrible happened" + handler.cause());
        }
        });
        }

        public void doSomethingWithTheItems(JsonObject items){
        // do something here with your items
        }
        }


        // Option 2 if you want to execute some other async method



        public class GetItemsService {
        public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
        new GetLocationsManager().getItems(vertx, routingContext);
        .compose(this::doSomethingAsyncWithTheItems)
        .setHandler(handler -> {
        if(handler.succeeded()){
        //Note4: handler.result() contains the result from the doSomethingAsyncWithTheItems call (future.complete(...))
        JsonObject didSomethingWithTheItems = handler.result();
        routingContext.response().end(didSomethingWithTheItems.encode());
        }else{
        // serve error response
        routingContext.response().end("something terrible happened");
        }
        });
        }

        public Future<JsonObject> doSomethingAsyncWithTheItems(JsonObject items){
        Future<JsonObject> future = Future.future();
        otherAsyncCallThatReturnsAFuture.setHandler(handler -> {
        if(handler.succeeded()){
        future.complete(...)
        }else{
        future.fail(...)
        }
        })
        return future;
        }
        }





        share|improve this answer













        I hope this helps i tried to add useful comments to your code.



        GetItemsManager



        public class GetItemsManager {
        public Future<JsonObject> getItems(Vertx vertx, RoutingContext routingContext) {
        //Note1: you can create the future here, no need to pass as a parameter
        Future<JsonObject> future = Future.future();
        ...
        webClient.post(80, Constants.API_URL, "/items")
        ...
        .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
        if (ar.succeeded()) {
        ...
        future.complete(data);
        } else {
        future.fail(new JsonObject().put("error", ar.cause().getMessage()).encode());
        }
        });
        return future;
        }
        }


        GetItemsService



        public class GetItemsService {
        public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
        new GetLocationsManager().getItems(vertx, routingContext) // returns Future<JsonObject>
        .setHandler(handler -> {
        //Note2: this codeblock is executed when your future is completed (or failed)
        if(handler.succeeded()){
        //Note3: handler.result() contains the result from the getItems call (future.complete(data))
        JsonObject items = handler.result();
        doSomethingWithTheItems(items);
        String itemsEncodedToString = items.encode();
        // serve the response
        routingContext.response().end(itemsEncodedToString);
        }else{
        // serve error response
        routingContext.response().end("something terrible happened" + handler.cause());
        }
        });
        }

        public void doSomethingWithTheItems(JsonObject items){
        // do something here with your items
        }
        }


        // Option 2 if you want to execute some other async method



        public class GetItemsService {
        public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
        new GetLocationsManager().getItems(vertx, routingContext);
        .compose(this::doSomethingAsyncWithTheItems)
        .setHandler(handler -> {
        if(handler.succeeded()){
        //Note4: handler.result() contains the result from the doSomethingAsyncWithTheItems call (future.complete(...))
        JsonObject didSomethingWithTheItems = handler.result();
        routingContext.response().end(didSomethingWithTheItems.encode());
        }else{
        // serve error response
        routingContext.response().end("something terrible happened");
        }
        });
        }

        public Future<JsonObject> doSomethingAsyncWithTheItems(JsonObject items){
        Future<JsonObject> future = Future.future();
        otherAsyncCallThatReturnsAFuture.setHandler(handler -> {
        if(handler.succeeded()){
        future.complete(...)
        }else{
        future.fail(...)
        }
        })
        return future;
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 23:38









        taygetostaygetos

        1,24311019




        1,24311019

























            3














            Try something like



            public class GetItemsService {
            public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
            Future<JsonObject> future = Future.future();
            new GetLocationsManager().getItems(future, vertx, routingContext);
            future.setHandler(h ->{
            routingContext.response().end(h.result().encode());
            });
            }
            }





            share|improve this answer
























            • Thanks for responding. How do I save the result in a variable, though?

              – aCarella
              Nov 21 '18 at 16:03











            • The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

              – taygetos
              Nov 21 '18 at 16:06











            • Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

              – aCarella
              Nov 21 '18 at 16:10






            • 1





              You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

              – taygetos
              Nov 21 '18 at 16:13






            • 1





              Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

              – taygetos
              Nov 21 '18 at 16:18
















            3














            Try something like



            public class GetItemsService {
            public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
            Future<JsonObject> future = Future.future();
            new GetLocationsManager().getItems(future, vertx, routingContext);
            future.setHandler(h ->{
            routingContext.response().end(h.result().encode());
            });
            }
            }





            share|improve this answer
























            • Thanks for responding. How do I save the result in a variable, though?

              – aCarella
              Nov 21 '18 at 16:03











            • The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

              – taygetos
              Nov 21 '18 at 16:06











            • Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

              – aCarella
              Nov 21 '18 at 16:10






            • 1





              You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

              – taygetos
              Nov 21 '18 at 16:13






            • 1





              Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

              – taygetos
              Nov 21 '18 at 16:18














            3












            3








            3







            Try something like



            public class GetItemsService {
            public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
            Future<JsonObject> future = Future.future();
            new GetLocationsManager().getItems(future, vertx, routingContext);
            future.setHandler(h ->{
            routingContext.response().end(h.result().encode());
            });
            }
            }





            share|improve this answer













            Try something like



            public class GetItemsService {
            public void retrieveItems(Vertx vertx, RoutingContext routingContext) {
            Future<JsonObject> future = Future.future();
            new GetLocationsManager().getItems(future, vertx, routingContext);
            future.setHandler(h ->{
            routingContext.response().end(h.result().encode());
            });
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 21 '18 at 15:56









            taygetostaygetos

            1,24311019




            1,24311019













            • Thanks for responding. How do I save the result in a variable, though?

              – aCarella
              Nov 21 '18 at 16:03











            • The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

              – taygetos
              Nov 21 '18 at 16:06











            • Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

              – aCarella
              Nov 21 '18 at 16:10






            • 1





              You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

              – taygetos
              Nov 21 '18 at 16:13






            • 1





              Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

              – taygetos
              Nov 21 '18 at 16:18



















            • Thanks for responding. How do I save the result in a variable, though?

              – aCarella
              Nov 21 '18 at 16:03











            • The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

              – taygetos
              Nov 21 '18 at 16:06











            • Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

              – aCarella
              Nov 21 '18 at 16:10






            • 1





              You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

              – taygetos
              Nov 21 '18 at 16:13






            • 1





              Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

              – taygetos
              Nov 21 '18 at 16:18

















            Thanks for responding. How do I save the result in a variable, though?

            – aCarella
            Nov 21 '18 at 16:03





            Thanks for responding. How do I save the result in a variable, though?

            – aCarella
            Nov 21 '18 at 16:03













            The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

            – taygetos
            Nov 21 '18 at 16:06





            The result is in your handler, you can access it with h.result() and it contains a JsonObject if your async call was successful and finished.

            – taygetos
            Nov 21 '18 at 16:06













            Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

            – aCarella
            Nov 21 '18 at 16:10





            Thanks. How do I access that outside of the lambda expression? I'll update my original post to show you what I've tried.

            – aCarella
            Nov 21 '18 at 16:10




            1




            1





            You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

            – taygetos
            Nov 21 '18 at 16:13





            You can not access to it outside. You have an asyncronous call, outside of the handler block your async call is may not yet finished.

            – taygetos
            Nov 21 '18 at 16:13




            1




            1





            Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

            – taygetos
            Nov 21 '18 at 16:18





            Why would you? you loose all the advantage that vertx provides you. But if you insist, check out the vertx-sync project

            – taygetos
            Nov 21 '18 at 16:18


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415119%2fhow-to-save-vert-x-webclient-result-and-return-it-in-method%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()