问题描述
在GWT有没有什么办法来等待异步调用完成?
我需要应对不断(这是一个登录屏幕,以便更迭意味着改变到实际的游戏和失败意味着停留在登录屏幕)。结果
这里是调用:
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;
}
我需要的检查方法返回的响应(或错误),而不是返回null。结果
我试着写的脑死亡的解决方案:`
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)
推荐答案
拥抱不同步,不打了!
在换句话说:让你的检查
异步方法也传递一个回调参数,而不是返回值;并通过回调 execRequest
(简单地回调的调用替换每一个分配给取值
)。
你不一定需要触发一个应用程序范围的事件总线上的事件,如洁建议:它有助于解耦,但是这并不总是你需要/想干什么
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.
这篇关于如何等待异步HTTP继续之前结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!