|
|
@@ -0,0 +1,32 @@
|
|
|
+package space.anyi;
|
|
|
+
|
|
|
+import java.util.concurrent.CompletableFuture;
|
|
|
+
|
|
|
+public class Cf05_ThenCompose {
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
+ CompletableFuture<String> userFuture = CompletableFuture.supplyAsync(() -> {
|
|
|
+ System.out.println("1. 查询用户");
|
|
|
+ return "用户:李雷";
|
|
|
+ });
|
|
|
+
|
|
|
+ // 如果使用 thenApply,返回的是嵌套的 CompletableFuture<CompletableFuture<String>>,
|
|
|
+ // 需要两层 join 才能取出结果,层级一多就变成"回调地狱"
|
|
|
+ CompletableFuture<CompletableFuture<String>> nested =
|
|
|
+ userFuture.thenApply(Cf05_ThenCompose::getOrder);
|
|
|
+ System.out.println("thenApply 拼出嵌套: " + nested.getClass().getSimpleName());
|
|
|
+ System.out.println(" 两层 join 取结果: " + nested.join().join());
|
|
|
+
|
|
|
+ // thenCompose 接受一个返回 CompletableFuture 的函数,
|
|
|
+ // 并将内层 Future 自动展平,保持链式调用只有一个层级
|
|
|
+ CompletableFuture<String> flat = userFuture.thenCompose(Cf05_ThenCompose::getOrder);
|
|
|
+ System.out.println("thenCompose 展平结果: " + flat.join());
|
|
|
+ }
|
|
|
+
|
|
|
+ // 模拟: 拿到用户后再异步查询他的订单
|
|
|
+ private static CompletableFuture<String> getOrder(String user) {
|
|
|
+ return CompletableFuture.supplyAsync(() -> {
|
|
|
+ System.out.println("2. 异步查询 \"" + user + "\" 的订单");
|
|
|
+ return "订单 O-10008";
|
|
|
+ });
|
|
|
+ }
|
|
|
+}
|