是否有CompletableFuture的.thenCompose()也会异常执行? [英] Is there a .thenCompose() for CompletableFuture that also executes exceptionally?
本文介绍了是否有CompletableFuture的.thenCompose()也会异常执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想再次执行 CompletableFuture
完成一次,无论第一个 CompletableFuture
是否完成( .thenCompose()
仅在执行正常完成时运行)。
I want to execute a CompletableFuture
once another CompletableFuture
finishes, regardless of whether or not the first one completes exceptionally (.thenCompose()
only runs when execution completes normally).
例如:
CompletableFuture.supplyAsync(() -> 1L)
.whenComplete((v, e) -> CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("HERE");
} catch(InterruptedException exc) {
return;
}
}))
.whenComplete((v, e) -> System.out.println("ALL DONE"));
此打印文件
ALL DONE
HERE
我希望成为这样
HERE
ALL DONE
最好不要将第二个 whenComplete()
嵌套在第一个内部。
preferably without nesting the second whenComplete()
inside the first.
我不在乎这里的返回结果/异常。
Note that I don't care about the returned result/exception here.
推荐答案
诀窍是使用。 handle((r,e)-> r)
以抑制错误:
The trick is to use .handle((r, e) -> r)
to suppress the error:
CompletableFuture.runAsync(() -> { throw new RuntimeException(); })
//Suppress error
.handle((r, e) -> r)
.thenCompose((r) ->
CompletableFuture.runAsync(() -> System.out.println("HELLO")));
这篇关于是否有CompletableFuture的.thenCompose()也会异常执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文