|
|
|
|
|
by philipwhiuk
397 days ago
|
|
Java's had `var` since Java 10 but apparently the author deliberately ignored that to make the example as wordy as possible. It's a little tiring to read a Java example with an entry-point (the public-static-void bit) and then a JavaScript example without one. If you strip that out the original Java is: var future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Data Fetched";
});
future.thenAccept(result -> System.out.println(result));
System.out.println("Prints first"); // prints before the async result
which is only obtuse due to checked exceptions.Arguably it's still a different thing you're doing, because it's not scheduling a task on a pool, it's creating a thread which sleeps for 10 seconds. |
|
The author uses `setTimeout` for javascript. The equivalent for Java is either the `Timer` class or a `ScheduledExecutorService`. Doing a `Thread.sleep` simply isn't how you should approach this.
With that in mind, if you want to use both these things and keep the completable future interface you'd have to do soemthing like this.