如何在不阻塞的情况下从嵌套的 CompletableFuture 返回值?

Yos*_*Yos 3 java future completable-future

getPrice()由于以下错误,我在使用方法返回汽车价格值时遇到问题:

no instance(s) of type variable(s) U exist so that CompletableFuture<U> conforms to Double inference variable U has incompatible bounds: equality constraints: Double lower bounds: CompletableFuture<U81345>
Run Code Online (Sandbox Code Playgroud)

我想要getPrice返回CompletableFuture<Double>,但它返回了CompletableFuture<CompletableFuture<Double>>,因为我正在从嵌套的 future 返回一个值。我可以调用.join()嵌套的 future,但我不想阻塞线程。这是我的代码:

no instance(s) of type variable(s) U exist so that CompletableFuture<U> conforms to Double inference variable U has incompatible bounds: equality constraints: Double lower bounds: CompletableFuture<U81345>
Run Code Online (Sandbox Code Playgroud)

chr*_*ke- 7

您正在寻找的操作(“返回 aContainer<U>而不是普通U”)通常称为flatMap,但 Java CompletionStageAPI 使用其他术语。正如 API 所示,thenApplyAsync应该接受 aT并返回 a U,它将被包装到 a 中CompletableFuture<U>,但您可以改为使用thenComposeAsync并返回您的CompletableFuture(作为“平面”返回类型)。

  • 在OP的示例中,@hitchhiker将“completedFuture(42)”更改为“completedFuture(42.0)”,因此所有分支一致返回“CompletableFuture&lt;Double&gt;”。 (2认同)
  • @hitchhiker我假设您已经应用了这个答案的使用“thenComposeAsync”的解决方案。 (2认同)
  • @hitchhiker,您应该将 *first* `thenApplyAsync` 替换为 `thenComposeAsync` ;其函数返回未来而不是值的一个。 (2认同)