我有一个方法doTransmit
,它返回一个CompletableFuture<T>
。我想循环调用doTransmit
并收集所有CompletableFuture<T>
并转换成CompletableFuture<List<T>>
并在所有收集到的List<T>
都用完后用CompletableFuture<T>
解析的CompletableFuture<DeliveryResponse> doTransmit(Notification notification, Receiver receiver, ContentMutator contentMutator) {
//send notification to this receiver
}
CompletableFuture<List<DeliveryResponse>> doTransmit(Notification notification, List<Receiver> receivers, ContentMutator contentMutator) {
List<CompletableFuture<DeliveryResponse>> completableFutures = new ArrayList<>();
receivers.forEach(receiver -> completableFutures.add(doTransmit(notification.clone(), receiver, contentMutator)));
CompletableFuture<List<DeliveryResponse>> listCompletableFuture = CompletableFuture.supplyAsync(ArrayList::new);
completableFutures.forEach(
completableFuture ->
completableFuture.thenCombine(listCompletableFuture,
((deliveryResponse, deliveryResponses) -> deliveryResponses.add(deliveryResponse))
)
);
return listCompletableFuture;
}
解决。
doTransmit(notification, receivers, null).thenAccept(list -> System.out.println(list.size()));
但是当我拨打第二个CompletableFuture
时,收到的列表为空。
我是$post_id = 1;
$user_ip = '0.0.0.0';
add_post_meta( $post_id, 'my_vote', $user_ip );
概念的新手。但是,我知道Javascript承诺。请帮忙。
答案 0 :(得分:1)
您需要一个Supplier<List<DeliveryResponse>>
来收集响应:
// your code
List<CompletableFuture<DeliveryResponse>> completableFutures = new ArrayList<>();
receivers.forEach(receiver -> completableFutures.add(doTransmit(notification.clone(), receiver, contentMutator)));
Supplier<List<DeliveryResponse>> responseCollector = () -> {
List<DeliveryResponse> result = new ArrayList<>();
// get the result for each... I think you need to try-catch this
receivers.forEach(r -> result.add(r.get());
return result;
}
,然后从中创建一个CompletableFuture
:
CompletableFuture<List<DeliveryResponse>> listFuture = CompletableFuture.supplyAsync(responseCollector);
return listFuture;
现在listFuture
通过为每个期货调用get
来收集结果。