note: I am new to play framework
For my Play! project, I require some form of asynchronous programming. Simply, I need to display a view, whilst doing processing in the background, followed by a redirect or a new form being rendered.
This question has been asked with no response. I have had a look on the Play Documentation pages, I didn't find any solution there.
What I have tried:
I attempted to modify the AsynchController
that is given with the play starter example
. However when navigating to http://localhost/message
, the function seemed to act more as a sleep instead of a scheduled task which is set and "forgotten" about, i.e. one can continue on with further coding.
AsynchController snippet: with own modification
public CompletionStage<Result> message() {
return getFutureMessage(5, TimeUnit.SECONDS).thenApplyAsync(s -> ok(views.html.User.Account.verified.render()), exec);
}
private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
CompletableFuture<String> future = new CompletableFuture<>();
actorSystem.scheduler().scheduleOnce(
Duration.create(time, timeUnit),
() -> future.complete("Waiting 5 seconds..."),
exec
);
return future;
}
route entry
GET /message controllers.AsyncController.message
Purpose:
My aim here was for the message Waiting 5 seconds...
to be displayed, followed by a +/- 5s delay. Thereafter it would reach the "future" (is this correct?) whereby it would render a view (or redirect to a controller), in this case the verified
page ( for account verified).
Am I on the right track with my original goal, where can I get a good example of something similar?
I have a simple solution, but you have to set up 2 entries in route.
The first entry displays the message "Waiting 5 seconds...", while at the same time it give an AJAX call to the second one. The controller for the second entry does the calculation/sleep for 5 seconds, and returns the desired content, which will be rendered on the first page by Javascript.
In the first webpage you would put something like:
axios.get(second-url)
.then(function (response) {
document.getElementById(someplaceholder).innerHTML=response.data.
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With