简体   繁体   English

Java-在异步thenCompose内部进行同步调用

[英]Java - sync call inside async thenCompose

Consider below code as I am not able to find better words to ask the question: 考虑下面的代码,因为我找不到更好的单词来问这个问题:

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

mandatoryComputationToGetManager() returns a CompletionStage mandatoryComputationToGetManager()返回一个CompletionStage

Now the doubt which I have is : 现在我的疑问是:

I wanted to call mandatoryComputationToGetManager() and after its computation I want getManagerById(...) to be called. 我想调用getManagerById(...) mandatoryComputationToGetManager()并在其计算后希望getManagerById(...)

I know there can be one way ie calling thenCompose() first to do mandatoryComputationToGetManager() and then do another thenCompose() on previous result for getManagerById() . 我知道有可能是单向的,即调用thenCompose()第一次做mandatoryComputationToGetManager()然后做一套thenCompose()在上一个结果getManagerById() But I wanted to figure out if there is a way without piping one thenCompose() o/p to another by which I can hold until mandatoryComputationToGetManager() result is ready. 但是我想弄清楚是否有一种方法可以不将一个thenCompose() o / p传递给另一个,我可以一直使用它直到mandatoryComputationToGetManager() thenCompose() mandatoryComputationToGetManager()结果准备好为止。

As far as I understand, in the above code getManagerById() will get called even if the result is not yet ready from mandatoryComputationToGetManager() , which I want to wait for so that once mandatoryComputationToGetManager() give the result getManagerById() should get computed asynchronously. 据我了解,在上面的代码getManagerById()将被调用即使结果是还没有准备好从mandatoryComputationToGetManager()我要等待,以便一旦mandatoryComputationToGetManager()得到的结果getManagerById()应该得到计算异步地。

Ideally, we should pipe one thenCompose o/p to another, but there is a way by which we can achieve what you are trying to do. 理想情况下,我们应该将一个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