如何避免Vert.x中的嵌套回调?

时间:2017-08-30 11:25:17

标签: callback vert.x

我有一些像这样的代码,使用vertx-jdbc-client

 client.getConnection(res -> {
            SQLConnection connection = res.result();
            connection.query("SELECT count(1) FROM T_User", res2 -> {
                connection.query("SELECT count(1) FROM T_Book", res3 -> {
                    System.out.println(res2.result().getRows() + "--" + res3.result().getRows());
                });
            });
        });

FutureRxJava?你可以使用你喜欢的任何一个,只需避免嵌套回调,谢谢。

1 个答案:

答案 0 :(得分:0)

期货与JavaScript承诺完全相同。创建一个返回Future<T>的方法,在此方法中执行异步调用。异步完成后,只需致电future.complete(<T>)

Future<JsonObject> getUsers(){
    Future<JsonObject> future = Future.future();
    client.getConnection(res -> {
        SQLConnection connection = res.result();
        connection.query("SELECT count(1) FROM T_User", res2 -> {
            connection.query("SELECT count(1) FROM T_Book", res3 -> {
                JsonObject rows = new JsonObject().put("res2",res2.result().getRows()).put("res2",res3.result().getRows());
                future.complete(rows);
                // In exception block, you can add
                // future.fail(Throwable);
            });
        });
    });
    return future;
}

RX正在投放。所以RX中的上述代码将成为:

Observable<JsonObject> getUsers(){
    return Observable.create(subscriber -> {
        client.getConnection(res -> {
            SQLConnection connection = res.result();
            connection.query("SELECT count(1) FROM T_User", res2 -> {
                connection.query("SELECT count(1) FROM T_Book", res3 -> {
                    JsonObject rows = new JsonObject().put("res2",res2.result().getRows()).put("res2",res3.result().getRows());
                    subscriber.onNext(rows);
                    subscriber.onCompleted();
                });
            });
        });

    }, Emitter.BackpressureMode.NONE);
}

使用RX API

Observable<Long> userCount = mongoClient.rxCount("users", query).toObservable();
Observable<Long> booksCount = mongoClient.rxCount("books", query).toObservable();


Observable
        .zip(userCount, booksCount, (userRes, booksRes) ->
                new JsonObject().put("user",userRes).put("books",booksRes)
        )
        .subscribe(objects -> {
            System.out.println(objects.getString("user"));
            System.out.println(objects.getString("books"));
        });

我使用了mongoClient,但您可以使用sqlClient