与 vertx 组合以获取顺序代码

nim*_*o23 3 vert.x

我有两个操作 step_1() 和 step_2() 并且想在 step_1() 之后执行 step_2()。

使用普通的Java,这将是:

step_1();
step_2();
Run Code Online (Sandbox Code Playgroud)

对于 vertx,我必须使用 vertx-compose()。我对吗?

根据https://groups.google.com/forum/#!topic/vertx/FuvlPLpoGOA,我不需要序列代码的期货。

“如果您想按顺序执行每个请求,则不需要期货。”

那么如何在不使用期货的情况下做到这一点呢?

我不知道,这是否重要:执行此代码的我的 Vertx 是“Worker”-Verticle。

@Override
public void start(Future<Void> fut) throws IOException {

Future<Void> step_1 = Future.future();
    step_1.compose(res -> {
        // If the future succeeded
        Future<Void> step_2 = step_1();

        step_2.compose(res2 -> {
            step_2();

        }, Future.future().setHandler(handler -> {
            // If the future failed
        }));

        //I dont need that
    }, Future.future().setHandler(handler -> {
        // If the future failed
    }));

}

public void step_1(){
..
}

public void step_2(){
..
}
Run Code Online (Sandbox Code Playgroud)

这是正确和最短(!)的方式吗?

y r*_*rao 6

下面是一个链接的例子Future,我已经让这个例子非常简单,但它展示了这个概念。

@RunWith(VertxUnitRunner.class)
public class Chaining {
    private Vertx vertx = Vertx.vertx();

    @Test
    public void futures_chaining(TestContext context) throws Exception {
        Async async = context.async();

        firstOperation()
                .compose((outcome) -> {
                    System.out.println(outcome);

                    return secondOperation();
                })
                .compose(outcome -> {
                    System.out.println(outcome);

                    /*
                      For stopping unit test we are returning this future                                                                                                                                                              
                      for production use-case this would be Future.succeededFuture 
                      or Future.failedFuture depending on your method outcomes
                     */
                    return Future.future(handle -> async.complete());
                });
    }

    private Future<String> firstOperation() {
        Future<String> future = Future.future();

        vertx.setTimer(1000, delay -> future.complete("First Operation Complete"));

        return future;
    }

    private Future<String> secondOperation() {
        Future<String> future = Future.future();

        vertx.setTimer(1000, delay -> future.complete("Second Operation Complete"));

        return future;
    }
}
Run Code Online (Sandbox Code Playgroud)