Vert.x 在不执行的情况下传递 Future

Vert.x passing a Future without execution

我有下面一段代码:

package starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start() {
    vertx.createHttpServer().requestHandler(req -> req.response().end("Hello Vert.x!")).listen(8080);

    cacheFirst("key", Future.future(h -> {
      System.out.println("Call external API");
      h.complete("Call external API");
    }))
    .onComplete(h -> System.out.println("Success"))
    .onFailure(t -> System.out.println("Failed"));
  }

  private Future<String> cacheFirst(String key, Future<String> task) {
    Future<String> getCache = Future.future(h -> {
      h.complete("ABCXYZ");
    });

    return getCache.onSuccess(res -> {
      System.out.println("Data from cache: " + res);
    }).onFailure(t -> {
      task.onSuccess(res -> {
        System.out.println("Store task result to cache");
      }).onFailure(tt -> {
        System.out.println("Do nothing");
      });
    });
  }

}

预期的控制台输出:

Data from cache: ABCXYZ
Success

实际控制台输出:

Call external API
Data from cache: ABCXYZ
Success

在函数 start 中,如何将 Future 作为参数传递给 cacheFirst 函数而不执行它?

在现实场景中,cacheFirst 函数会首先尝试从缓存存储中获取数据,如果找到,则无需执行提供的 future (Future<string> task)例如,调用对外部 API.

的请求

复制者:https://github.com/triet-truong/vertx-application

只需将其包裹在 Supplier 内即可产生预期结果!
https://github.com/triet-truong/vertx-application/commit/6391c1b5d6b5f0e9b927ab0a9834b3ce6f0edf7f

cacheFirst("key", () -> Future.future(h -> {
      System.out.println("Call external API");
      h.complete("Call external API");
    }))
    .onComplete(h -> System.out.println("Success"))
    .onFailure(t -> System.out.println("Failed"));
private Future<String> cacheFirst(String key, Supplier<Future<String>> task) {
    Future<String> getCache = Future.future(h -> {
      h.complete("ABCXYZ");
    });

    return getCache.onSuccess(res -> {
      System.out.println("Data from cache: " + res);
    }).onFailure(t -> {
      task.get().onSuccess(res -> {
        System.out.println("Store task result to cache");
      }).onFailure(tt -> {
        System.out.println("Do nothing");
      });
    });
  }