gpt4 book ai didi

java - 如何在传播结果或错误时调用 CompletableFuture 回调?

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:13 27 4
gpt4 key购买 nike

我正在尝试 .exceptionally 和 .handle,但它们似乎不起作用。在 Scala 中,您可以使用类似于 finally block 的闭包调用 future 的方法(它在异常和成功时运行)并且它按原样向上传播异常或成功。

我试过了...

    CompletableFuture<Object> future = newFuture.handle((r, e) -> {
if(r != null)
return r;
else if(e != null)
return e;
else
return new RuntimeException("Asdf");
});

Assert.assertTrue(future.isCompletedExceptionally());

但是由于异常的结果(多么奇怪),该测试失败了,因为 future 完全成功。

最佳答案

使用CompletableFuture#whenComplete(BiConsumer) .它的 javadoc 状态

Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes.

When this stage is complete, the given action is invoked with the result (or null if none) and the exception (or null if none) of this stage as arguments. The returned stage is completed when the action returns. If the supplied action itself encounters an exception, then the returned stage exceptionally completes with this exception unless this stage also completed exceptionally.

换句话说,无论成功还是失败,它都会被调用,并且会传播初始 future 的状态(除非 BiConsumer 抛出异常)。

CompletableFuture<String> future2 = newFuture.whenComplete((r, e) -> {
// consume the result
});

如果您需要转换结果(在您的示例中,您不需要),那么您可以使用 handle 并自己传播内容。

关于java - 如何在传播结果或错误时调用 CompletableFuture 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com