我有这种奇怪的类型CompletableFuture< CompletableFuture< byte []>>但我想要CompletableFuture< byte []>.这可能吗?
public Future<byte[]> convert(byte[] htmlBytes) { PhantomPdfMessage htmlMessage = new PhantomPdfMessage(); htmlMessage.setId(UUID.randomUUID()); htmlMessage.setTimestamp(new Date()); htmlMessage.setEncodedContent(Base64.getEncoder().encodeToString(htmlBytes)); CompletableFuture<CompletableFuture<byte[]>> thenApply = CompletableFuture.supplyAsync(this::getPhantom,threadPool).thenApply( worker -> worker.convert(htmlMessage).thenApply( pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent()) ) ); }
解决方法
其文档中有一个
bug,但
CompletableFuture#thenCompose
系列方法相当于flatMap.它的声明也应该给你一些线索
public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
thenCompose获取接收者CompletableFuture的结果(称之为1)并将其传递给您提供的函数,该函数必须返回自己的CompletableFuture(称之为2). ThenCompose返回的CompletableFuture(称之为3)将在2完成时完成.@H_403_11@
在你的例子中@H_403_11@
CompletableFuture<Worker> one = CompletableFuture.supplyAsync(this::getPhantom,threadPool); CompletableFuture<PdfMessage /* whatever */> two = one.thenCompose(worker -> worker.convert(htmlMessage)); CompletableFuture<byte[]> result = two.thenApply(pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent()));