什么是java CompletableFuture相当于scala Future救援和处理 [英] What is java CompletableFuture equivalent of scala Future rescue and handle

查看:118
本文介绍了什么是java CompletableFuture相当于scala Future救援和处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 CompletableFuture 有一个方法句柄与scala 未来的句柄基本上将成功和异常全部转换为成功 map flatMap 上游(或 thenApply thenCompose 在java世界中) 。

I see that CompletableFuture has a method handle that is the same as that of scala Future's handle basically converting success and exceptions all to success to be map and flatMap upstream(or thenApply and thenCompose in java world).

相当于twitter的未来 rescue (或scala future recoverWith )?

What is the equivalent of twitter future rescue(or scala future recoverWith) in java though?

scala中的rescue 基本上就像旧的java try .... catch ,然后重新抛出更多信息,这样可以很好用。例如,在 twitterFuture.handle scalaFuture.recover 中,返回单位为 U 所以你返回一个回复。在 twitterFuture.rescue scalaFuture.recoverWith 中,它返回 Future [U] 所以可以采取某些例外,添加更多信息并返回 Future.exception(xxxxx)

rescue in scala is basically like the old java try....catch, then rethrow with more information so it can be nice to use. For example in twitterFuture.handle or scalaFuture.recover the return unit is U so you return a response. In twitterFuture.rescue or scalaFuture.recoverWith, it returns Future[U] so one can take certain exceptions, add more info and return Future.exception(xxxxx)

推荐答案

对于 recover ,如果您不需要返回超类并希望吞下所有异常,则可以使用 格外

For recover, if you don't need to return a superclass and want to swallow all exceptions, you could just use exceptionally:

CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.exceptionally(_exc -> defaultValue);

否则,您需要使用 handle 获取 CompletableFuture< CompletableFuture< U>> ,然后使用 thenCompose 崩溃它:

Otherwise, you need to use handle to get a CompletableFuture<CompletableFuture<U>>, and then use thenCompose to collapse it:

CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.handle((v, e) -> {
        if (e == null) {
            return CompletableFuture.completedFuture(v);
        } else {
            // the real recoverWith part
            return applyFutureOnTheException(e);
        }
    }).thenCompose(Function.identity());

这篇关于什么是java CompletableFuture相当于scala Future救援和处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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