我的方法如何 return 在 lambda 表达式中计算出一个值?

How can my method return a value computed within a lambda expression?

这是我的代码的简化版本:

public void pairing() {
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            JsonObject pairing = response.result().body().toJsonObject(); // what I want to return
        }
}

这会向 localhost:6660/request 发出 POST 请求,我创建了一个名为 pairing 的新 JsonObject 来存储对该请求的响应。我可以在请求的 lambda 表达式内部处理配对,但理想情况下,我可以 return JsonObject 到调用 pairing() 的方法并从那里处理它。

我试过这个:

public JsonObject pairing() {
    JsonObject pairing = new JsonObject();
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            pairing = response.result().body().toJsonObject();
        }
    return pairing;
}

但它不起作用,因为我收到 "pairing must be final or effectively final" 错误。有什么方法可以从这个方法 return "pairing" 以便我可以在我的程序的其他地方访问它?或者我可能以错误的方式接近这个?

使用期货:

public Future<JsonObject> pairing() {
        Future<JsonObject> future = Future.future();
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            future.complete(response.result().body().toJsonObject());
        }
    return future;
}

现在调用这个函数:

pairing().setHandler(r -> {
    r.result // This is your JSON object
});

WebClient 将异步执行。您正在尝试的是同步的,使用 WebClient 是不可能的,而且同步调用在 vert.x 中将是阻塞调用。这也是黄金法则,不要阻塞事件循环。