Chaining with thenApply and thenCompose
Transform results with thenApply and flatMap async steps with thenCompose to avoid nested futures.
thenApply: Transform the Result
thenApply(Function) applies a synchronous function to the result of a completed future, returning a new future of the transformed type. It does not start a new async task.
CompletableFuture<String> nameFuture = CompletableFuture
.supplyAsync(() -> 42L) // CF<Long>
.thenApply(id -> "User#" + id); // CF<String>
System.out.println(nameFuture.join()); // "User#42"thenApplyAsync: Transform on a Thread
thenApplyAsync runs the transformation function on the ForkJoinPool (or a supplied executor), freeing the completing thread immediately.
CompletableFuture<String> result = fetchUserAsync()
.thenApplyAsync(user -> serialize(user)); // runs on pool threadAll lessons in this course
- Creating and Completing CompletableFutures
- Chaining with thenApply and thenCompose
- Combining Futures: allOf and anyOf
- Error Handling and Async HTTP Pipeline