我正在尝试编写一系列步骤,以便可以避免 if
的大嵌套链和else
通过创建返回 CompletableFuture<Boolean>
的方法来调用以诸如......的方式
client.connect(identifier).thenCompose(b -> client.authenticate())
.thenCompose(b -> client.sendSetting(settings))
.thenCompose(b -> client.saveSettings())
.thenCompose(b -> client.sendKey(key))
.thenCompose(b -> client.setBypassMode(true))
.thenCompose(b -> client.start())
.whenComplete((success, ex) -> {
if(ex == null) {
System.out.println("Yay");
} else {
System.out.println("Nay");
}
});
如果客户端方法返回 CompletableFuture<Boolean>
必须在链中的每个 lambda 中决定是否继续处理,并且不提供在其中一个调用失败时提前中止的方法。我宁愿让电话返回 CompletableFuture<Void>
并使用Exceptions
控制是否 1) 链中的每个连续步骤执行以及 2) 整个链成功的最终确定。
我在 CompletableFuture<Void>
上找不到哪个方法交换 thenCompose
使事情正常运转(更不用说编译了)。
最佳答案
public class FutureChaings {
public static CompletableFuture<Void> op(boolean fail) {
CompletableFuture<Void> future = new CompletableFuture<Void>();
System.out.println("op");
Executors.newScheduledThreadPool(1).schedule(() -> {
if(fail) {
future.completeExceptionally(new Exception());
}
future.complete(null);
}, 1, TimeUnit.SECONDS);
return future;
}
public static void main(String[] args) {
op(false).thenCompose(b -> op(false)).thenCompose(b -> op(true)).whenComplete((b, ex) -> {
if(ex != null) {
System.out.println("fail");
} else {
System.out.println("success");
}
});
}
}
我能够设计一个按照我想要的方式运行的示例。所以我知道怎样才能得到我想要的东西。现在要弄清楚编译器在我的真实代码中不喜欢什么。感谢您的评论。
关于java - 具有异常处理功能的 CompletableFuture 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120649/