Java8 CompletableFuture recoveryWith 等价物?例如异常但返回 CompletableFuture<U>; [英] Java8 CompletableFuture recoverWith equivalent? eg exceptionally but return CompletableFuture&lt;U&gt;

查看:24
本文介绍了Java8 CompletableFuture recoveryWith 等价物?例如异常但返回 CompletableFuture<U>;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有看到处理具有异步结果的异常的明显方法.例如,如果我想重试异步操作.我期待这样的事情,但是 handleAsync 并没有像你想象的那样做——它异步地在另一个线程上运行回调.在这里返回 CompletionStage 是不正确的.当天的危险问题:thenApplythenCompose 来说就像 exceptionally 对什么?

I don't see an obvious way to handle an exception with an asynchronous result. For example, 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 thenCompose as exceptionally 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;
} 

推荐答案

在尝试找出在 Java 8 中执行 Scala 的 recoveryWith 的正确方法时遇到了很多挫折,我最终只编写了自己的.我仍然不知道这是否是最好的方法,但我创建了类似的东西:

After a lot of frustration in trying to figure out the proper way of doing Scala's recoverWith in Java 8, I ended up just writing my own. I still don't know if this is the best approach, but I created something like:

public RecoveryChainAsync<T> recoverWith(Function<Throwable,
                                         CompletableFuture<T>> fn);

通过反复调用recoverWith,我将恢复链中的函数排入队列,并通过handle"自己实现恢复流程.RecoveryChainAsync.getCompletableFuture() 然后返回整个链的代表 CompletableFuture.希望这会有所帮助.

With repeated calls to recoverWith, I queue up the functions inside the recovery chain and implement the recovery flow myself with "handle". RecoveryChainAsync.getCompletableFuture() then returns a representative CompletableFuture for the entire chain. Hope this helps.

这篇关于Java8 CompletableFuture recoveryWith 等价物?例如异常但返回 CompletableFuture<U>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆