如何在vert.x中正确翻译这段代码?
通常,在春季或带有模板引擎的简单sevlet中,我会这样做,以输出html响应
function test(request, response) {
templatecontext tc = getContext();
init conditions
if (condition1) {
retrieve data from db ({
asyncresult -> {
tc.put("data1", data1)
})
} else if (condition2) {
other code
if (condition 2.1) {
retrieve data from db ({
asyncresult -> {
tc.put("data2", data2)
})
}
}
get other data from db and put in context
template.eval("templatefile", tc)
write to response
}
问题是,从数据库中检索数据是asyncresult的处理程序,因此我不能授予模板评估是使用data1或data2进行的,因为检索异步时不会掉入回调地狱。
我不太了解rxjava2,但是我觉得我想用勺子杀死豆子。
答案 0 :(得分:1)
您可以使用futures和composition。请参见vertx-examples
回购中的ComposeExample
:
public class ComposeExample extends AbstractVerticle {
@Override
public void start() throws Exception {
Future<String> future = anAsyncAction();
future.compose(this::anotherAsyncAction)
.setHandler(ar -> {
if (ar.failed()) {
System.out.println("Something bad happened");
ar.cause().printStackTrace();
} else {
System.out.println("Result: " + ar.result());
}
});
}
private Future<String> anAsyncAction() {
Future<String> future = Future.future();
// mimic something that take times
vertx.setTimer(100, l -> future.complete("world"));
return future;
}
private Future<String> anotherAsyncAction(String name) {
Future<String> future = Future.future();
// mimic something that take times
vertx.setTimer(100, l -> future.complete("hello " + name));
return future;
}
}