简体   繁体   中英

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

I have a method where I make an async call conditionally. Below is the simplified version of it. I want it to return if the 'condition' is met.

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, "")));
    }

}

How could I do that?

As per documentation you can't call blocking operations directly from an event loop, as that would prevent it from doing any other useful work. So how can you do this?

It's done by calling executeBlocking specifying both the blocking code to execute and a result handler to be called back asynchronous when the blocking code has been executed.

            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());
            });

It turned out I was missing the basics of async programming..

It suffices to 'return' after the Successful Future is handed.

Otherwise, the code continues to execute and makes the call anyway.

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, "")));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM