簡體   English   中英

Java-在異步thenCompose內部進行同步調用

[英]Java - sync call inside async thenCompose

考慮下面的代碼,因為我找不到更好的單詞來問這個問題:

CompletionStage<Manager> callingAsyncFunction(int developerId) {
    return getManagerIdByDeveloperId(developerId)
           .thenCompose(id ->
             getManagerById(id, mandatoryComputationToGetManager(id)))
}

mandatoryComputationToGetManager()返回一個CompletionStage

現在我的疑問是:

我想調用getManagerById(...) mandatoryComputationToGetManager()並在其計算后希望getManagerById(...)

我知道有可能是單向的,即調用thenCompose()第一次做mandatoryComputationToGetManager()然后做一套thenCompose()在上一個結果getManagerById() 但是我想弄清楚是否有一種方法可以不將一個thenCompose() o / p傳遞給另一個,我可以一直使用它直到mandatoryComputationToGetManager() thenCompose() mandatoryComputationToGetManager()結果准備好為止。

據我了解,在上面的代碼getManagerById()將被調用即使結果是還沒有准備好從mandatoryComputationToGetManager()我要等待,以便一旦mandatoryComputationToGetManager()得到的結果getManagerById()應該得到計算異步地。

理想情況下,我們應該將一個thenCompose o / p傳遞給另一個,但是有一種方法可以實現您想要的工作。

  CompletionStage<String> callingAsyncFunction(int developerId) {
    return getManagerIdByDeveloperId(developerId)
        .thenCompose(id -> getManagerById(id, mandatoryComputationToGetManager()));
  }

  private CompletionStage<String> getManagerById(
      Integer id, CompletionStage<String> stringCompletionStage) {
    return stringCompletionStage.thenApply(__ -> "test");
  }

  private CompletionStage<String> mandatoryComputationToGetManager() {
    return CompletableFuture.completedFuture("test");
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM