簡體   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