java - 如果返回失败的阶段,为什么 thenCombine 结果不能异常完成?
问题描述
以下代码片段调用thenCombine ,并没有在whenComplete设置异常(它打印No exception
):
CompletableFuture.completedFuture(true)
.thenCombine(CompletableFuture.completedFuture(true),
(x,y) -> {
return CompletableFuture.failedStage(new RuntimeException());
})
.whenComplete( (myVal, myEx) -> {
if (myEx == null) {
System.out.println("No exception");
} else {
System.out.println("There was an exception");
}
});
但是,下面调用thenCompose的类似代码确实设置了一个异常:
CompletableFuture.completedFuture(true)
.thenCompose(
x -> {
return CompletableFuture.failedStage(new RuntimeException());
})
.whenComplete( (myVal, myEx) -> {
if (myEx == null) {
System.out.println("No exception");
} else {
System.out.println("There was an exception");
}
});
为什么在 BiFunction 实际上返回失败阶段时thenCombine
返回正常完成?CompletionStage
解决方案
在你的第一个例子CompletableFuture.failedStage(new RuntimeException())
中是结果。CompletableFuture
返回的由thenCombine
完成CompletableFuture.failedStage(new RuntimeException())
。
当您不链接调用时,它会变得更加清晰:
CompletableFuture<Boolean> first = CompletableFuture.completedFuture(true);
CompletableFuture<Boolean> second = CompletableFuture.completedFuture(true);
CompletableFuture<CompletionStage<?>> yourQuestion =
first.thenCombine(second, (x, y) ->
CompletableFuture.failedStage(new RuntimeException()));
对于您的第二个示例,您需要thenCompose
仔细阅读以下文档:
返回一个新的 CompletionStage,它使用与给定函数返回的 CompletionStage 相同的值完成。
在你的函数中thenCompose
返回一个失败CompletableFuture
,它的结果被用作CompletableFuture
返回的结果thenCompose
:a RuntimeException
。
推荐阅读
- angular - 如何将内部类 ID 插入 Angular 8 中的 href 链接?.html 组件
- sql-server - 用 count 和 group by 减去 SQL 查询
- android - 如何在 TextInputLayout android 中更改 setEndIconDrawable 的可见性(可见、不可见或消失)?
- firebase - Google firebase Auth 后如何获取用户 YouTube Data API 的 API 密钥
- android - 如何允许用户在没有身份验证的情况下发送电子邮件
- reactjs - 使用 react-hooks 查找总数并打印平均值
- reactjs - 将导出表反应为 pdf
- julia - 如何在 Julia 数据框中删除/删除空行和 NaN?
- laravel - 按列排序的关系?
- django - 如何为表单中的多对多字段添加样式(Django)