4

In GWT is there any way to wait for asynchronous call to complete? I need the response to continue (It's a login screen so succes means changing to the actual game and failure means staying in the login screen).
Here is the call:

private void execRequest(RequestBuilder builder)
{
    try
    {
        builder.sendRequest(null, new RequestCallback()
        {
            public void onError(Request request, Throwable exception)
            {
                s = exception.getMessage();
            }

            public void onResponseReceived(Request request,
                    Response response)
            {
                s = response.getText();
            }
        });
    } catch (RequestException e)
    {
        s = e.getMessage();
    }
}

And here is the calling method:`

public String check()
{
    s = null;
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, baseUrl
            + "check&user=" + user + "&password=" + password);
    execRequest(builder);
    return s;
}

I need the check method to return the response (or error) and not to return null.
I tried the brain-dead solution of writing:`

while (s == null);

To wait for the call to finish but that just crushed the page in development mode.
(chrome said page is unresponsive and suggested to kill it)

Daniel Shaulov
  • 2,354
  • 2
  • 16
  • 25
  • see this post http://stackoverflow.com/questions/11086591/prevent-method-call-until-async-call-completes-gwt-platform/17932909#17932909 – Tony Jul 29 '13 at 19:54

2 Answers2

6

Embrace asynchrony, don't fight it!

In other words: make your check method asynchronous too, passing a callback argument instead of returning a value; and pass a callback to execRequest (simply replace every assignment to s with a call to the callback). You don't necessarily need to fire an event on an application-wide event bus, as Jai suggested: it helps in decoupling, but that's not always what you need/want.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
3

You should not check for completion that way. The best design practice here is to fire a custom event when the login async call completes.. and when you receive the event (through the event bus) you do the remaining tasks.

read up on http://code.google.com/webtoolkit/articles/mvp-architecture.html#events

Jai
  • 3,549
  • 3
  • 23
  • 31