java CompletableFuture 链接结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37265253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CompletableFuture chaining results
提问by plzdontkillme
I am trying to chain the calls/results of the methods to the next call. I get compile time error methodE because if am not able to get the reference of objB from the previous call.
我试图将方法的调用/结果链接到下一个调用。我得到编译时错误 methodE 因为如果我无法从上一次调用中获得 objB 的引用。
How can I pass the result of the previous call to the next chain? Have I completely misunderstood the process?
如何将上一个调用的结果传递给下一个链?我完全误解了这个过程吗?
Object objC = CompletableFuture.supplyAsync(() -> service.methodA(obj, width, height))
.thenApply(objA -> {
try {
return service.methodB(objA);
} catch (Exception e) {
throw new CompletionException(e);
}
})
.thenApply(objA -> service.methodC(objA))
.thenApply(objA -> {
try {
return service.methodD(objA); // this returns new objB how do I get it and pass to next chaining call
} catch (Exception e) {
throw new CompletionException(e);
}
})
.thenApply((objA, objB) -> {
return service.methodE(objA, objB); // compilation error
})
.get();
回答by Misha
You could store intermediate CompletableFuture
in a variable and then use thenCombine
:
您可以将中间存储CompletableFuture
在变量中,然后使用thenCombine
:
CompletableFuture<ClassA> futureA = CompletableFuture.supplyAsync(...)
.thenApply(...)
.thenApply(...);
CompletableFuture<ClassB> futureB = futureA.thenApply(...);
CompletableFuture<ClassC> futureC = futureA.thenCombine(futureB, service::methodE);
objC = futureC.join();