>> result = tokenFuture.thenA-6ren">
gpt4 book ai didi

Java 多嵌套 CompletionStage 相当于 "flatMap"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:55 30 4
gpt4 key购买 nike

所以考虑到我有以下示例:

CompletionStage<String> tokenFuture = getToken();

CompletionStage<CompletionStage<CompletionStage<CompletionStage<Boolean>>>> result = tokenFuture.thenApply(token -> {

WSRequest request = ws.url(url).setHeader("Authorization", "Bearer " + token);

CompletionStage<WSResponse> response = request.post(json);

return response.thenApply(r -> {
if (r.getStatus() == 201) {
return CompletableFuture.supplyAsync(() -> CompletableFuture.supplyAsync(() -> true));
} else {
return getToken().thenApply(t -> {
WSRequest req = ws.url(url).setHeader("Authorization", "Bearer " + t);
return req.post(json).thenApply(b -> b.getStatus() == 201);
});
}
});

});

我的问题是整个 CompletionStage<CompletionStage<CompletionStage<CompletionStage<Boolean>>>>多嵌套 future 类型。是否可以将其减少到 CompletionStage<Boolean>通过使用类似 flatMap 的东西在 Scala 中还是有其他方法可以做到这一点?

最佳答案

是的,您正在寻找 thenCompose(fn)操作:

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage as the argument to the supplied function.

此方法采用一个函数作为参数,该函数采用此完成阶段的结果并返回另一个完成阶段。

因此,您可以拥有以下内容:

CompletionStage<String> tokenFuture = getToken();

CompletionStage<Boolean> result = tokenFuture.thenCompose(token -> {

WSRequest request = ws.url(url).setHeader("Authorization", "Bearer " + token);

CompletionStage<WSResponse> response = request.post(json);

return response.thenCompose(r -> {
if (r.getStatus() == 201) {
return CompletableFuture.supplyAsync(() -> true);
} else {
return getToken().thenCompose(t -> {
WSRequest req = ws.url(url).setHeader("Authorization", "Bearer " + t);
return req.post(json).thenApply(b -> b.getStatus() == 201);
});
}
});

});

关于Java 多嵌套 CompletionStage 相当于 "flatMap"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307422/

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