3 回答

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
似乎asyncClass.getChild是異步執(zhí)行的(因?yàn)樗枰卣{(diào))。如果是這種情況,那么您當(dāng)前的實(shí)現(xiàn)就足夠了(下面的更正除外)。
asyncClass.getChild("test", listChild -> {
if (listChild.isOk()) {
future.complete(listChild.isSuccess().getData());
} else {
future.complete(null); //you need to do this
//or future.completeExceptionally(exception) if this is a failure
}
});
如果您想getChild在單獨(dú)的線程中運(yùn)行,那么我強(qiáng)烈建議您重新設(shè)計(jì)該方法以使其返回List<String>而不是進(jìn)行回調(diào)。這種設(shè)計(jì)使得getChild異步運(yùn)行變得很尷尬。
interface AsyncFS {
fun getChild(path: String): List<String> //don't trust my syntax
}
然后以這種方式異步運(yùn)行它:
CompletableFuture<List<String>> future =
CompletableFuture.supplyAsync(() -> asyncClass.getChild("test"));
return future;

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
更改您的getChild()方法以返回 aCompletableFuture<ListChild>而不是將回調(diào)作為參數(shù)。
沒(méi)有實(shí)際的代碼,我無(wú)法確切地說(shuō)出這必須如何完成,但基本上代碼看起來(lái)像
CompletableFuture<ListChild> result = new CompletableFuture<>();
processAsynchronously(path, result);
return result;
whereprocessAsynchronously()執(zhí)行異步計(jì)算,并在某些時(shí)候調(diào)用result.complete(listChild).
然后調(diào)用者將能夠輕松地將調(diào)用鏈接起來(lái),例如
CompletableFuture<List<String>> result = asyncClass.getChild("test")
.thenAcceptAsync(listChild -> {
if (listChild.isOk()) {
return listChild.isSuccess().getData()
}
return null;
}, executor);
或使用他想要的任何執(zhí)行程序進(jìn)行任何其他處理。
如您所見(jiàn),這比強(qiáng)制執(zhí)行特定類型的回調(diào)要靈活得多。

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
提供 Runnable 或 Supplier 作為參數(shù)CompletableFuture.runAsync()或supplyAsync()
return CompletableFuture.runAsync(() -> {
doSomething();
}, optionalExecutor);
添加回答
舉報(bào)