繁体   English   中英

在 CompletableFuture 的 whenComplete() 之前返回的方法

[英]Method returning before CompletableFuture's whenComplete()

我第一次使用CompletableFuture's whenComplete

在我的用例中,我想调用 REST api 并获取其结果。 对这些结果执行一些操作并返回输出。

我想过使用CompletableFuture.supplyAsync()进行这个 REST 调用并使用whenComplete()来获取结果。

下面是我目前使用的示例代码:

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;

但是在调试时我注意到在执行第 #2 行后,执行了 #10 并且函数返回,然后在 #3 上开始执行。

这不是我所期望的。 我希望它是连续的。

我怎样才能做到这一点?

PS 旁注,我不想 CompletableFuture.get(),因为它不处理InterruptedException

您故意使用异步的东西,然后抱怨它不是同步的......如果您希望它是同步的,请完全删除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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM