async await - vertx: returning final response of API only after getting response of all internal calls -


i writing api in vertx requires downstream system called multiple times. want final api response returned after downstream call completed. because of highly async nature of vertx, final reponse getting returned before getting downstream responses.

public void externalcall(routingcontext routingcontext) {     map<int, some_class> map = new hashmap();     for(int i=0; i<10; i++) {         some_class = internalcall(i);         map.put(i, some_class);     }     routingcontext.response().putheader("content-type", "application/json;      charset=utf-8").end(json.encodeprettily(map)); } 

what best possible way tackle above problem in vertx?

yes correct, vert.x async need rely on futures or rx.

using completablefuture

list<completablefuture> futureslist = new arraylist<>(); for(int i=0; i<10; i++) {     futureslist.add(internalcall(i)); } completablefuture         .allof(futureslist.toarray(new completablefuture[futureslist.size()]))         .handle((res, ex) -> {             routingcontext.response().putheader("content-type", "application/json;charset=utf-8").end(json.encodeprettily(futureslist));             return null; }); 

the handle execute when of internal calls done. return type of internalcall method should completablefuture

public completablefuture<jsonobject> internalcall(int i) {     completablefuture<jsonobject> promise = new completablefuture<>();     someasynccall(i, res -> {             if(res.succeeded()){                 promise.complete(res.result());             }else{                 promise.completeexceptionally(new exception(res.cause()));             }         });     return promise; } 

you can go rx, have cleaner , smaller code.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -