英文:
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响应进行进一步处理,请帮忙。
英文:
vertx.setPeriodic(1000, id -> {
//api call
if (count == 4){
vertx.cancelTime(id);
}
});
Now the problem is I don't want a fix 1000 ms time, I just want to call the api 4 times and then go with final api response for further processing , please help.
答案1
得分: 2
一种方法是使用递归方法。
因此,您可以将类似以下的内容实现为方便的入口点
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()) {
// 出现错误,执行错误处理..
return;
}
final YourResultType result = reply.result();
// 处理您的结果..
});
另一种方法是将API调用作为Future放入列表中,然后使用 CompositeFuture.all、CompositeFuture.join 等并行执行此列表,而不是一个接一个地执行。
英文:
One way is to use a recursive approach.
Therefore you can implement something like this as an convenient entrypoint
private Future<YourResultType> callApiNTimes(final int repetitions) {
final Promise<YourResultType> p = Promise.promise();
recursiveApiCalls(p, 0, repetitions);
return p.future();
}
Recursion implemented as following
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());
});
}
At the end implement yourRawApiCall
and then use it like this
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 approach would be to put your API calls as Futures in a list
and execute this list in parallel with CompositeFuture.all, CompositeFuture.join, .. instead of one after another.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论