我有一个异步方法

asyncClass.getChild("test", listChild -> {
  if (listChild.isOk()) {
  List<String> list = listChild.isSuccess().getData()
  }
  return null;
});

如何将这个异步调用包装在CompletableFuture中?
final CompletableFuture<List<String>> future = new CompletableFuture<>();
asyncClass.getChild("test", listChild -> {
  if (listChild.isOk()) {
    future.complete(listChild.isSuccess().getData());
  }
  return null;
});
return future;

一切正常,但我希望一切都在单独的线程调用中工作
interface AsyncFS {
    fun getChild(path: String, onResult: (Result<List<String>>) -> Unit)
}

最佳答案

看来asyncClass.getChild是异步执行的(因为它需要回调)。如果是这样,那么您当前的实现就足够了(下面的更正除外)。

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在单独的线程中运行,那么我强烈建议您重新设计该方法,以使其返回List<String>而不是进行回调。这种设计使异步运行getChild变得很尴尬。
interface AsyncFS {
    fun getChild(path: String): List<String> //don't trust my syntax
}

然后以这种方式异步运行它:
CompletableFuture<List<String>> future =
    CompletableFuture.supplyAsync(() -> asyncClass.getChild("test"));
return future;

09-10 23:10