简体   繁体   English

Java - 使用CompletableFuture链中断执行序列

[英]Java - Break execution sequence using CompletableFuture chain

I am new to Java and am using CompletableFutures to perform async operations such as below: 我是Java新手,我正在使用CompletableFutures来执行异步操作,如下所示:

public CompletionStage<Either<ErrorResponse, Response>> insertOrUpdate(String actor, String key) {
    return this.objectDAO.getByKey(key)
            .thenApply(mapDOToContainer(key))
            .thenApply(mergeContainerToDO(key, actor))
            .thenComposeAsync(this.objectDAO.UpdateFn())
            .thenApply(DBResult::finished)
            .thenApply(finished -> {
                if (finished) {
                    Response response = Response.ok().build();
                    return Either.right(response);
                } else {
                    return Either.left(ErrorResponse.create("Error", 400));
                }
            });
}

Now I need to modify this so that if the get fails then I perform the above chain, but if it succeeds then I need to break this chain and return from the function with an Either object containing an ErrorResponse. 现在我需要修改它,这样如果get失败,那么我执行上面的链,但是如果它成功,那么我需要打破这个链并从包含ErrorResponse的Either对象的函数返回。

How can I break this processing chain? 我该如何打破这个处理链? I know I can pass a flag to each function in the chain and achieve this by performing the actions in the functions based on the value of the flag. 我知道我可以将一个标志传递给链中的每个函数,并通过根据标志的值执行函数中的操作来实现此目的。 I was hoping there is a better way to do this. 我希望有更好的方法来做到这一点。

Thanks!! 谢谢!!

I would rewrite your code. 我会重写你的代码。

  • Don't use Either for errors, Java has exception 不要将Either用于错误,Java有异常
  • Don't return a CompletionStage from your DAO 不要从DAO返回CompletionStage
  • Use exceptionally from CompletableFuture, it is designed for this 从CompletableFuture中exceptionally使用,它专为此而设计

Then do this: 然后这样做:

public CompletionStage<Response> insertOrUpdate(String actor, String key) {
    return CompletableFuture.supplyAsync(() -> this.objectDAO.getByKey(key))
            .thenApply(mapDOToContainer(key))
            .thenApply(mergeContainerToDO(key, actor))
            .thenComposeAsync(this.objectDAO.UpdateFn())
            .thenApply(DBResult::finished)
            .thenApply(finished -> {
                Response response = Response.ok().build();
                return response;
            })
            .exceptionally(e -> ErrorResponse.create("Error", 400));
}

The DAO should be something like this: DAO应该是这样的:

class ObjectDAO {
    public Object getByKey(String key) {
        if (keyNotFound) {
            throw new NoSuchElementException();
        }

        return new Object();
    }
}

You may have to make sure that ErrorResponse is a subclass of Response to make this work. 您可能必须确保ErrorResponse是Response的子类才能使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM