gpt4 book ai didi

java - 打破 Completable Future 的 then apply 链

转载 作者:行者123 更新时间:2023-12-01 14:17:40 25 4
gpt4 key购买 nike

我有很多这样的电话。问题是下一个电话完全取决于前一个电话。如果没有任何对话从他们那里获取消息是没有意义的,所以我只想打破这个链条。我读了几个关于 Holger 答案的主题,但我觉得我仍然不完全理解这一点。有人可以根据这段代码给我一些例子吗?

public CompletableFuture<Set<Conversation>> fetchConversations(List<Information> data, String sessionId)
{
return myservice
.get(prepareRequest(data, sessionId))
.thenApply(HtmlResponse::getDocument)
.thenApply(this::extractConversationsFromDocument);
}
public CompletableFuture<Elements> fetchMessagesFromConversation(String Url, String sessionId)
{
return mySerice
.get(prepareRequest(url, sessionId))
.thenApply(HtmlResponse::getDocument)
.thenApply(this::extractMessageFromConversation);
}

最佳答案

从您的任何链式步骤中抛出异常将跳过所有后续步骤:不会调用任何 thenApply() 回调, future 将在异常发生时得到解决。你可以用它来打破你的链条。例如,考虑以下代码:

public CompletableFuture<Set<Conversation>> fetchConversations(List<Information> data, String sessionId) {
return myservice
.get(prepareRequest(data, sessionId))
.thenApply(HtmlResponse::getDocument)
.thenApply(value -> {
if (checkSomeCondition(value))
throw new CompletionException(new CustomException("Reason"));
return value;
})
.thenApply(this::extractConversationsFromDocument)
.exceptionally(e -> {
// the .thenApply(this::extractConversationsFromDocument) step
// was not executed
return Collections.emptySet(); //or null
});
}

您可以添加一个步骤来检查上一步返回的值,并根据某些情况抛出异常。

然后在最后一个 .thenApply 之后,您可以添加一个 exceptionally 处理程序并返回一个空的 Setnull或其他不成功的结果。

您也可以省略 exceptionally 处理程序。在这种情况下,您必须在链的末尾捕获异常,最终调用 .get():

try {
Set<Conversation> conversations = fetchConversations(data, id).get();
} catch (InterruptedException e) {
// handle the InterruptedException
e.printStackTrace();
} catch (ExecutionException e) {
// handle the ExecutionException
// e.getCause() is your CustomException or any other exception thrown from the chain
}

关于java - 打破 Completable Future 的 then apply 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48512453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com