Jas*_*onG 6 java java-8 completable-future
我没有看到使用异步结果处理异常的明显方法.例如,如果我想重试异步操作.我希望这样的东西,但handleAsync不会做你认为它做的事情 - 它在异步运行另一个线程上的回调.在这里返回CompletionStage是不正确的.当天的危害问题:thenApply就是thenCompose因为exceptionally是为了什么?
CompletionStage<String> cf = askPong("cause error").handleAsync((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
}
});
Run Code Online (Sandbox Code Playgroud)
askPong问演员的地方:
public CompletionStage<String> askPong(String message){
Future sFuture = ask(actorRef, message, 1000);
final CompletionStage<String> cs = toJava(sFuture);
return cs;
}
Run Code Online (Sandbox Code Playgroud)
Mis*_*sha 11
这是你想要的?
askPong("cause error")
.handle( (pong, ex) -> ex == null
? CompletableFuture.completedFuture(pong)
: askPong("Ping")
).thenCompose(x -> x);
Run Code Online (Sandbox Code Playgroud)
此外,...Async除非您打算异步执行所提供函数的主体,否则不要使用这些方法.所以,当你做类似的事情
.handleAsync((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
})
Run Code Online (Sandbox Code Playgroud)
您要求if-then-else在单独的线程中运行.因为askPong返回a CompletableFuture,所以可能没有理由异步运行它.
在尝试找出在 Java 8 中执行 Scala 恢复功能的正确方法时经历了很多挫折,最终我只编写了自己的方法。我仍然不知道这是否是最好的方法,但我创建了类似的方法:
public RecoveryChainAsync<T> recoverWith(Function<Throwable,
CompletableFuture<T>> fn);
Run Code Online (Sandbox Code Playgroud)
通过重复调用recoverWith,我将恢复链内的函数排队,并使用“handle”自行实现恢复流程。RecoveryChainAsync.getCompletableFuture() 然后返回整个链的代表性 CompletableFuture。希望这可以帮助。