这是我的代码的简化版本:
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 表达式内部处理配对,但理想情况下,我能够将 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;
}
但它不起作用,因为我收到“配对必须是最终的或有效的最终”错误。有什么方法可以从此方法返回“配对”,以便我可以在程序的其他地方访问它吗?或者我可能以错误的方式处理这个问题?
最佳答案
使用 future :
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 中将是阻塞调用。这也是黄金法则,不要阻塞事件循环。
关于java - 我的方法如何返回在 lambda 表达式中计算的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45468565/