有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有异常处理的java CompletableFuture链接

我正在尝试组成一个步骤链,这样我就可以通过创建返回CompletableFuture<Boolean>的方法来避免ifelse调用的大型嵌套链,例如

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以使事情正常工作(更不用说编译了)


共 (1) 个答案

  1. # 1 楼答案

    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");
                }
            });
        }
    }
    

    我能够设计出一个符合我要求的例子。所以我知道为了得到我想要的东西需要做些什么。现在来找出编译器不喜欢我的真实代码的地方。谢谢你的评论