We use Futures in vertx in examples like:
Future<JsonObject> fetchVehicle = getUserBookedVehicle(routingContext, client);
fetchVehicle.compose(vehicleJson -> vehicleDoor(routingContext, client, vehicleJson, lock)).setHandler(
asyncResult -> {
if (asyncResult.succeeded()) {
LOG.info("Door operation succeeded with result {}", asyncResult.result().encode());
handler.handle(Future.succeededFuture(new AsyncReply(200, "OK")));
}
else {
handler.handle(Future.failedFuture(asyncResult.cause()));
}
});
where we handle 2 calls for example.
OR I have another snippet where I can handle any number of methods:
List<Future> futures = new ArrayList<>();
conversation.getRequestList().forEach(req -> {
Future<Message<Object>> senderFuture = Future.future();
vertx.eventBus().send(AbstractOEMClientVerticle.ADDRESS, JsonObject.mapFrom(req), deliveryOptions, senderFuture.completer());
// sent successfully. save the replyAddress and the conversation for later/callback
log.info("Saving the conversation for the request.", conversation.getReplyAddress());
pendingCommands.put(req.getBody().getString(MSG_ID), conversation);
futures.add(senderFuture);
});
CompositeFuture.all(futures).setHandler(ar -> {
if (ar.succeeded()) {
handler.handle(Future.succeededFuture());
} else {
log.error("forwardToVWClient VW got result : {}", ar.cause());
handler.handle(Future.failedFuture(ar.cause()));
}
});
Here we are chaining all the requests in the conversation.getRequestList()
without knowing their count in advance.
But the shortcoming of .all()
method is that, we have no control on the order.
How can I chain any number of methods with Vertx Futures (without knowing the exact count of the calls) ?
EDIT:
The official guide talks about sequential composition but the example given has 3 calls. It does not explain how to do it for arbitrary number of calls.
See "Sequential composition" in http://vertx.io/docs/vertx-core/java/
I hope it is clear.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…