问题描述
我没有看到使用异步结果处理异常的明显方法。
例如,如果我想重试异步操作。我希望这样的东西,但handleAsync不会做你认为它做的事情 - 它在异步运行另一个线程上的回调。在这里返回CompletionStage是不正确的。当天的危险问题:然后应用是异常的,然后组成是什么。
I don't see an obvious way to handle an exception with an asynchronous result.Eg, if I want to Retry an async operation. I would expect something like this, however handleAsync doesn't do what you think it does - it runs the callbacks on another thread asynchronously. Returning a CompletionStage here is not correct. Jeopardy question of the day: thenApply is to exceptionally as thenCompose is to what.
CompletionStage<String> cf = askPong("cause error").handleAsync((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
}
});
askPong问演员:
Where askPong asks an actor:
public CompletionStage<String> askPong(String message){
Future sFuture = ask(actorRef, message, 1000);
final CompletionStage<String> cs = toJava(sFuture);
return cs;
}
推荐答案
这就是你在找什么for?
Is this what you are looking for?
askPong("cause error")
.handle( (pong, ex) -> ex == null
? CompletableFuture.completedFuture(pong)
: askPong("Ping")
).thenCompose(x -> x);
此外,请勿使用 ... Async
方法除非您打算异步执行所提供函数的主体。所以,当你做类似
Also, do not use the ...Async
methods unless you intend for the body of the supplied function to be executed asynchronously. So when you do something like
.handleAsync((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
})
您要求在单独的线程中运行 if-then-else
。由于 askPong
返回 CompletableFuture
,因此可能没有理由以异步方式运行它。
You are asking for the if-then-else
to be run in a separate thread. Since askPong
returns a CompletableFuture
, there's probably no reason to run it asynchronously.
这篇关于Java8 CompletableFuture recoverWith等价?例如,异常但返回CompletableFuture< U>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!