We have an internal API that executes the code in a lambda and returns a Boolean result in a CompleteStage:
我们有一个内部API,它在lambda中执行代码,并在CompleteStage中返回布尔结果:
private CompletionStage<Boolean> foo1() {
return internalAPI(param -> {
// first step
// second step
return Boolean.TRUE;
});
}
Now the second step is implemented as an async task as well:
现在,第二步也被实现为一个cpdec任务:
private CompletionStage<Boolean> foo2() {
return internalAPI(param -> {
// first step
secondStep(); // <-- how to execute this and get result of it?
// if second step finished successfully then ...
return Boolean.TRUE;
});
}
private CompletionStage<Boolean> secondStep() {
// do something
}
How do I make the secondStep()
run in the foo2()
, make sure it's finished before hitting return Boolean.TRUE;
?
如何让Second Step()在foo2()中运行,并确保它在按Return Boolan.TRUE;之前完成?
--- EDIT ---
--编辑
This is the brief implementation of internalAPI()
, basically it's trying to do all steps in one transaction and if one of the steps is failed the transaction can be rollback:
这是内部API()的简短实现,基本上它尝试在一个事务中完成所有步骤,如果其中一个步骤失败,则事务可以回滚:
public <A> CompletableFuture<A> internalAPI(Function<Connection, A> block) {
return CompletableFuture.supplyAsync(() -> doTransaction(block),
new HttpExecutionContext(databaseContext).current());
}
public <T> T doTransaction(Function<Connection, T> block) {
Transaction tx = Ebean.beginTransaction();
try (Connection sql2oConnection = sql.open()) {
spliceConnections(sql2oConnection, tx.getConnection());
T ret = block.apply(sql2oConnection);
Ebean.commitTransaction();
return ret;
} finally {
Ebean.endTransaction();
}
}
更多回答
This is going to depend on internalAPI
, which you haven't shown us.
这将取决于内部API,您还没有向我们展示它。
(It looks like internalAPI
fundamentally expects a Function, to which the answer is "this is impossible." You can probably chain it with other CompletionStages, but that'll require going outside whatever internalAPI does; there isn't a generic way to do this.
(看起来内部API基本上需要一个函数,而答案是“这是不可能的”。您可能会将它与其他CompletionStage链接在一起,但这需要在内部API所做的任何事情之外进行;没有一种通用的方法可以做到这一点。
What about just doing "first step" inside the function passed to internalAPI
, then executing secondStep
via e.g., thenCompose
?
如果只在传递给内部化API的函数中执行“第一步”,然后通过例如thenCompose执行第二步,会怎么样?
@LouisWasserman I added implementation of the internalAPI
@LouisWasserman我添加了internalAPI的实现
As Slaw said, something like foo1().thenCompose(x -> internalAPI(param -> { secondStep(); return Boolean.TRUE; });
, except that you have to check the boolean values if you keep using boolean values as success indicator, instead of using exceptions/failed futures.
正如Slaw所说,类似于foo1().thenCompose(x->IntraldAPI(param->{Second Step();Return Boolan.TRUE;}));,只是如果您继续使用布尔值作为成功指示器,而不是使用异常/失败的未来,则必须检查布尔值。
我是一名优秀的程序员,十分优秀!