因此,考虑到我有以下示例:

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>>>>多嵌套的将来类型。是否可以通过在Scala中使用类似CompletionStage<Boolean>的方式将其简化为flatMap,还是有另一种方式来做到这一点?

最佳答案

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



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

因此,您可能需要执行以下操作:

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/

10-09 02:09