[英]Method returning before CompletableFuture's whenComplete()
I'm using CompletableFuture's whenComplete
for the first time.我第一次使用
CompletableFuture's whenComplete
。
In my use case I want to call a REST api and fetch its result.在我的用例中,我想调用 REST api 并获取其结果。 Perform some operations on those results and return the output.
对这些结果执行一些操作并返回输出。
I thought of making this REST call using CompletableFuture.supplyAsync()
& use whenComplete()
to fetch the result.我想过使用
CompletableFuture.supplyAsync()
进行这个 REST 调用并使用whenComplete()
来获取结果。
Below is the sample code I'm currently using:下面是我目前使用的示例代码:
1. String myOutput = null;
2. CompletableFuture.supplyAsync(() -> callMyRestService(myUrl))
3. .whenComplete((myResponseWrapper, exception) -> {
4. if (exception != null) {
5. logUtil.error("GET", exception.toString());
6. } else if (myResponseWrapper != null) {
7. myOutput = myResponseWrapper.getName();
8. }
9. });
10. return myOutput;
But upon debugging I noticed that after executing line #2, #10 is executed and function returns, then later execution of on #3 starts.但是在调试时我注意到在执行第 #2 行后,执行了 #10 并且函数返回,然后在 #3 上开始执行。
This is not what I expecting.这不是我所期望的。 I wanted it to be sequential.
我希望它是连续的。
How can I achieve this?我怎样才能做到这一点?
PS On side note, I did not wanted to CompletableFuture.get(), because the way it does not handle InterruptedException
. PS 旁注,我不想 CompletableFuture.get(),因为它不处理
InterruptedException
。
You are deliberately using something that's async and then complaining it's not synchronous... Remove the CompletableFuture
entirely if you want it to be synchronous.您故意使用异步的东西,然后抱怨它不是同步的......如果您希望它是同步的,请完全删除
CompletableFuture
。
try {
SomeClass myResponseWrapper = callMyRestService(myUrl)
return myResponseWrapper.getName();
}
catch (Exception e) {
logUtil.error("GET", exception.toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.