Loading...
Important Notice - Forums is archived

To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Product icon
TUTORIAL

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.

Calling javascript synchronously

Nicklas Karlsson
2 years ago Apr 15, 2020 12:50pm
Nicklas Karlsson
2 years ago Apr 16, 2020 9:37am
Leif Åstrand
2 years ago Apr 16, 2020 12:46pm

executeJs and all its derivatives are always asynchronous. What you can maybe do in this kind of situation is to run the whole procedure in a dedicated worker thread instead of running it from the "main" thread that handles updates to the Vaadin UI. You would then use ui.access to submit the executeJs job to a Vaadin thread and have the worker thread block on e.g. a CompletableFuture that will be completed from a Vaadin thread that eventually gets the result back from the user's browser.

Nicklas Karlsson
2 years ago Apr 20, 2020 12:22pm
Leif Åstrand
2 years ago Apr 20, 2020 2:57pm

UI.push() is not enough. You must allow the session lock to be released so that the request that asynchronously brings the return value back to the server can be processed.

In practice, this means that the worker thread does something along these lines

CompletableFuture<Integer> future = new CompletableFuture<>();
ui.access(() -> {
  ui.getPage().executeJs("return 1+1").then(Integer.class, value -> future.complete(value));
});
Integer result = future.get();

Alternatively, you can use toCompletableFuture() on the pending JS result. In that case, you need to pass it through an instance field or an explicit handover structure since you cannot modify local variables from inside the thread. If you pass through a field, then need to use accessSynchronously instead of access so that the field is actually written before you block on its value.

Last updated on Apr, 20th 2020
Nicklas Karlsson
2 years ago Apr 21, 2020 5:35am
Thang Le
2 years ago Apr 21, 2020 4:36pm
Nicklas Karlsson
2 years ago Apr 21, 2020 5:37pm
Nicklas Karlsson
2 years ago Apr 23, 2020 9:24am
Leif Åstrand
2 years ago Apr 23, 2020 1:09pm
Nicklas Karlsson
2 years ago Apr 24, 2020 6:22am
Leif Åstrand
2 years ago Apr 24, 2020 1:01pm
Nicklas Karlsson
2 years ago Apr 27, 2020 5:10am
Marco Zanon
2 years ago Aug 31, 2020 1:59pm
Jean-Christophe Gueriaud
2 years ago Sep 01, 2020 5:11am
Marco Zanon
2 years ago Sep 01, 2020 4:56pm
Jean-Christophe Gueriaud
2 years ago Sep 01, 2020 5:49pm
Marco Zanon
2 years ago Sep 03, 2020 12:48pm

Thanks Jean-Christophe for teaching me something about invocation of server methods from client-side: my code is much cleaner now.

Thanks, MZ

Enver Haase
1 month ago Sep 12, 2022 3:29pm