O.Housein O.Housein - 1 month ago 10
reST (reStructuredText) Question

why i couldn't get the result from the first request vert.x?

public class Ussd {

private static Logger logger = LogManager.getLogger(Ussd.class);
private static String query;

public static void ussdMessages(RoutingContext routingContext){
String codeService = routingContext.getBodyAsJson().getString("codeService");
query=getServiceQuery(codeService);
System.out.println("queryy : "+query);
}


public static String getServiceQuery(String codeService){
JsonObject params = new JsonObject();
params.put("QUERY", Queries.DB_SELECT_SERVICE_QUERY);
params.put("PARAMS", new JsonArray().add(codeService));
System.out.println(params);
DB.select(params, res -> {
if (res.succeeded()) {
query = res.result().getJsonArray("results").getJsonArray(0).getString(0);
System.out.println(query);
} else {
query = res.cause().getMessage();
}
});
return query;
}


}

the methode getServiceQuery returns my exact result and i stock it into static query but after recall inside methode ussdMesages it returns null from the first request using Postman , the seconde request it returns the exact result. i don't know why ?

Answer

Your getServiceQuery method does async work(DB.select), so in your case you are returning the query before it getting processed. Change the return type of the function from String to Future.

public class Ussd {

    private static Logger logger = LogManager.getLogger(Ussd.class);
    private  static  String query;

    public static void ussdMessages(RoutingContext routingContext){
        String codeService = routingContext.getBodyAsJson().getString("codeService");
        getServiceQuery(codeService).setHandler(r -> {
                System.out.println("queryy : "+r.result());
            });

    }


    public static Future<String> getServiceQuery(String codeService){
        Future<String> future = Future.future();
        JsonObject params = new JsonObject();
        params.put("QUERY", Queries.DB_SELECT_SERVICE_QUERY);
        params.put("PARAMS", new JsonArray().add(codeService));
        System.out.println(params);
        DB.select(params, res -> {
            if (res.succeeded()) {
               query = res.result().getJsonArray("results").getJsonArray(0).getString(0);
                System.out.println(query);
                future.complete(query);
            } else {
                future.fail(res.cause().getMessage());
            }
        });
        return future;
    }

}