获取 CompletableFuture.supplyAsync 的结果

Getting the result of a CompletableFuture.supplyAsync

我有这段代码:

CompletableFuture
    .supplyAsync(() -> {
        return  smsService.sendSMS(number);
    }).thenApply(result -> {
        LOG.info("SMS sended " + result);
    });

但是我遇到了一个编译错误:

The method thenApply(Function<? super Boolean,? extends U>) in the type CompletableFuture<Boolean> is not applicable for the arguments ((<no type> result) -> {})

您想使用 thenAccept 而不是 thenApply

thenApply 采用 Function 形式

public interface Function<T, R> {
    R apply(T t);
}

thenAccept 采用 Consumer 形式

public interface Consumer<T> {
    void accept(T t);
}

您提供的 lambda 没有 return 值;它是无效的。因为泛型类型参数不能为空,所以您的 lambda 不能转换为 Function 接口。另一方面,Consumer 有一个 void return 类型,lambda 可以满足。