如何使用java中的vertx调用api4次然后继续

How to use vertx in java to call api 4 times and then proceed

vertx.setPeriodic(1000, id -> {
    //api call
    if (count == 4){
        vertx.cancelTime(id); 
    }
});

现在的问题是我不想修复 1000 毫秒的时间,我只想调用 api 4 次,然后使用最终的 api 响应进行进一步处理,请帮忙.

一种方法是使用递归方法。

因此您可以实现类似这样的东西作为方便的入口点

private Future<YourResultType> callApiNTimes(final int repetitions) {
    final Promise<YourResultType> p = Promise.promise();

    recursiveApiCalls(p, 0, repetitions);

    return p.future();
}

递归实现如下

private void recursiveApiCalls(final Promise<YourResultType> p, final int counter, final int maxRepetitions) {
    yourRawApiCall().onComplete(reply -> {
        if (reply.failed()) {
            p.fail(reply.cause());
            return;
        }

        if (counter < maxRepetitions) {
            recursiveApiCalls(p, counter + 1, maxRepetitions);
            return;
        }

        p.complete(reply.result());
    });
}

最后实现yourRawApiCall然后像这样使用

callApiNTimes(4).onComplete(reply -> {
    if (reply.failed()) {
        // Something went wrong, do your error handling..
        return;
    }

    final YourResultType result = reply.result();

    // Do something with your result..
});

Antoher 的方法是将您的 API 调用作为 Futures 放入列表中 并与 CompositeFuture.all, CompositeFuture.join 并行执行此列表,.. 而不是一个接一个地执行。