如何在vertx中使用for循环进行异步调用

时间:2020-01-05 17:04:42

标签: vertx-verticle vertx-eventbus

想要对每个请求执行获取查询,然后想要添加所有结果,然后对每个结果进行更新查询,最后只想在函数的未来响应中返回结果,但由于获取和更新查询是在单独的事件循环线程中执行。我该怎么办?

public Future<List<String>> method(List<Request> requests, SQLConnection connection) {
    List<String> results = new ArrayList<>();
    Future<List<String>> future = Future.future();
    try {
        Function<AsyncResult<ResultSet>, List<String>> buildFromResultSet = query -> {
            List<JsonObject> resulSetJson = query.result().getRows();
            return resulSetJson.stream().map(rs -> {
                return rs.getString("code");
            }).collect(Collectors.toList());
        };
        for (Request request : requests) {
            Future<List<String>> responseFuture = queryExecutor.queryWithParams(SELECT_ITEMS, buildFromResultSet, request.getQuantityChange());
            responseFuture.setHandler(handler -> {
                if (handler.succeeded()) {
                    results.addAll(handler.result());
                } else {
                    LOGGER.error("Error ", handler.cause());
                    future.fail(handler.cause());
                }
            });
            LOGGER.info("size :{}", results.size());
            connection.batchWithParams(UPDATE_STATUS, results.stream().map(result -> new JsonArray().add(result)).collect(Collectors.toList()), query -> {
                if (query.succeeded()) {
                    List<Integer> updated = query.result();
                    if (updated == null || updated.isEmpty() || updated.stream().anyMatch(u -> u == 0))
                        future.fail(new ValidationException(MessageDetail.builder().message("0 rows processed").messageType(MessageType.ERROR).build()));
                    else
                        future.complete(results);
                    LOGGER.info("Successfully executed : {}", results);
                } else {
                    future.fail(query.cause());
                }
            });
        }
    } catch (Exception e) {
        LOGGER.error("Error ", e);
        future.fail(e);
    }
    return future;
}

0 个答案:

没有答案