[英]Return CompletableFuture<Void> or CompletableFuture<?>?
[英]Return a value inside a CompletableFuture in another CompletableFuture and return that future
我想在另一个 CompletableFuture 中的 CompletableFuture(在本例中为 clonedWorld)中获取一个值并返回该未来。 这是我的代码,我被困在这里:
@Override
public CompletableFuture<SlimeWorld> asyncCloneWorld(String worldName, String newWorld) {
loadWorldAsync(worldName).whenComplete((slimeWorld, throwable) -> {
if (throwable != null || slimeWorld.isEmpty()) {
plugin.getLogger().log(Level.SEVERE, "Impossibile caricare il mondo template!", throwable);
return;
}
try {
SlimeWorld clonedWorld = slimeWorld.get().clone(newWorld, loader, true);
} catch (IOException | WorldAlreadyExistsException e) {
plugin.getLogger().log(Level.SEVERE, "Non è stato possibile clonare il mondo: " + worldName, e);
}
});
return ?;
}
您的问题是whenComplete()
仅将BiConsumer
作为参数,它无法处理返回的CompletableFuture
的结果——除非抛出异常。
如果你想改变结果(这里是Optional<SlimeWorld>
或SlimeWorld
或null
的例外),使用的适当方法是handle()
。 因此,传递给handle()
的 lambda 应该返回最终结果(克隆的世界或null
)。
由于CompletableFuture
是一个流利的 API,您可以从asyncCloneWorld()
返回handle()
调用的结果:
public CompletableFuture<SlimeWorld> asyncCloneWorld(String worldName, String newWorld) {
return loadWorldAsync(worldName).handle((slimeWorld, throwable) -> {
if (throwable != null || slimeWorld.isEmpty()) {
plugin.getLogger().log(Level.SEVERE, "Impossibile caricare il mondo template!", throwable);
return null;
}
try {
return slimeWorld.get().clone(newWorld, loader, true);
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Non è stato possibile clonare il mondo: " + worldName, e);
return null;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.