【发布时间】:2020-09-08 03:54:41
【问题描述】:
下面如何增强功能,其中getB、getC、getD与A有依赖关系,需要等待A完成后才能调用。 但是我希望在 A 完成后同时调用 B C D。
感谢大家的帮助
注意:所有 dbService 都返回一个 completableFuture
CompletableFuture<List<A>> a= dbService.getA(request);
a.thenApply(a-> {
try {
return dbService.getB(a);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
})
.thenAccept (result->{
//do something with B
});
a.thenApply(a-> {
try {
return dbService.getC(a);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
})
.thenAccept (result->{
//do something with C
});
a.thenApply(a-> {
try {
return dbService.getD(a);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
})
.thenAccept (result->{
//do something with D
});
【问题讨论】:
-
使用
thenApplyAsync? -
U 表示将 all 与 applyAsync 结合?如果是这样,我如何重新传递参数 A
-
什么意思?只需将所有三个
thenApply替换为thenApplyAsync。 -
我的意思是有没有将所有三个功能结合起来?谢谢
-
您说,您希望 B、C 和 D 同时运行。所以不,你不能在一个函数中拥有这些和这些同时运行的调用。这也没有任何意义。如果要简化代码,请将 dbService 方法修复为不抛出
InterruptedException,因为返回表示异步操作的对象,但声明抛出表示等待操作的异常是矛盾的.