如何从Java中另一个CompletableFuture的thenApply返回CompletableFuture?

时间:2020-02-19 20:59:56

标签: java promise future chaining completable-future

我对Java CompletableFuture的概念是陌生的,因此除thenApply之外我对它及其功能一无所知

我有一个要求,我必须测试thenApply A CompletableFuture块中的某些条件。如果满足条件,则返回null,否则返回另一个CompletableFuture B ,以便在下一个thenApply中,结果将为 B

基本上,我正在尝试执行以下操作:

CompletableFuture<String> A = ......
CompletableFuture<Boolean> B = ......

A.thenApply((res) -> {
  if (res.equals("hey")) {
   return null;
  } else {
   return B;
  }
})
.thenApply((bResult) -> { // At this point, I want it to act as if I was calling B.thenApply

   //some function;
})

这可能吗?我是否可以从另一个CompletableFuture返回一个CompletableFuture,以便链上的下一个thenApply实际上是返回的thenApply中的一个CompletableFuture

此外,如果我想在某些情况下取消下一个thenApply。我该怎么办?

0 个答案:

没有答案