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=" + us开发者_如何学编程er + "&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)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.
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
精彩评论