*Vert.x*: 如何在同步代码中处理

*Vert.x*: How to handle in synchronous code

我有一个方法可以有条件地进行异步调用。下面是它的简化版本。如果满足 'condition',我希望它成为 return。

private void myMethod(RoutingContext routingContext, Handler<AsyncResult<AsyncReply>> handler) {
    //...
    if (condition) {
        // this does not work
        handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

    // here I do an async call and use the handler appropriately
    HttpClientRequest productRequest = client.getAbs(url, h -> h.bodyHandler(bh -> {
           // works  
           handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

}

我该怎么做?

根据文档,您不能直接从事件循环中调用阻塞操作,因为那样会阻止它执行任何其他有用的工作。那你怎么能做到这一点?

这是通过调用 executeBlocking 来完成的,它指定要执行的阻塞代码和在执行阻塞代码时异步回调的结果处理程序。

            vertx.executeBlocking(future -> {
              // Call some blocking API that takes a significant amount of time to return
              String result = someAPI.blockingMethod("hello");
              future.complete(result);
            }, res -> {
              System.out.println("The result is: " + res.result());
            });

原来我错过了异步编程的基础知识..

提交成功的未来后'return'就足够了。

否则,代码将继续执行并进行调用。

private void myMethod(RoutingContext routingContext, Handler<AsyncResult<AsyncReply>> handler) {
    //...
    if (condition) {
        // this does not work
        handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
        return; // !!!!! 
    }

    // here I do an async call and use the handler appropriately
    HttpClientRequest productRequest = client.getAbs(url, h -> h.bodyHandler(bh -> {
           // works  
           handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

}