问题描述
我有一些使用 CompletableFuture
运行异步的流程,例如:
I have certain flow that runs async using the CompletableFuture
, e.g.:
foo(...)
.thenAccept(aaa -> {
if (aaa == null) {
break!
}
else {
...
}
})
.thenApply(aaa -> {
...
})
.thenApply(...
所以如果我的 foo()
返回 null
(以后)我需要很快打破,否则,流程会继续。
So if my foo()
returns null
(in a future) I need to break very soon, otherwise, the flow continue.
For现在我必须在每个未来的块中检查 null
;但这很难看。
For now I have to check for null
all the way, in every future block; but that is ugly.
会不会这可以用 CompletableFuture
?
使用 CompletableFuture
,您可以定义一个接一个地执行的异步任务流。例如,您可以说:
With CompletableFuture
you can define your flow of async tasks, that are executed one after the other. For example, you may say:
我的问题是打破这个流和说:
My question is about breaking this flow and saying:
这就是我打破流量的意思。
This is what I meant by 'breaking the flow`.
推荐答案
您的问题很一般,所以答案可能并不完全适用于您。解决此问题的方法有很多种,可能适用于不同情况。
Your question is very general, so the answer might not exactly apply to you. There are many different ways to address this that might be appropriate in different situations.
在评估 CompletableFuture 与
.thenCompose
:
foo().thenCompose(x -> x == null
? completedFuture(null)
: completedFuture(x)
.then.....(...)
.then.....(...)
).join();
这篇关于打破CompletableFuture的流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!